フォーム認証を備えたWebサーバーとSignalRハブをホストする別のサーバー。フォーム認証Cookieを使用して、以下のコードを使用して現在のユーザーを抽出します。これはHttpModuleを使用して可能ですが、SignalRを使用する場合、HttpModuleは使用できません。
私がやりたいことをアーカイブする他の方法はありますか?
public class AuthorizationHubModule : HubPipelineModule
{
public AuthorizationHubModule()
{
}
protected override bool OnBeforeConnect(IHub hub)
{
var cookies = hub.Context.Request.Cookies;
if (cookies.ContainsKey(".ASPXAUTH") == true)
{
// Get the user, populate the Thread.CurrentUser...
Cookie cookie = cookies[".ASPXAUTH"];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
GenericIdentity identity = new GenericIdentity(ticket.Name);
GenericPrincipal principal = new GenericPrincipal(identity, new string[0]);
// Cannot do this because User is readonly (this is possible in a normal HttpModule)
//hub.Context.User = principal;
}
}
return base.OnBeforeConnect(hub);
}
}
後は、SignalRに関連付けられたIPrincipalを設定します。
回答:
回答№1は1間違っていない場合は、コンテキストからログインしているユーザーのユーザー情報を抽出しようとしています。それが正しい場合、これは以下を行うことで簡単に達成できます。
- [Authorize]属性をハブクラスに追加します。
- 次に、Context.User.Identityを使用してユーザーIDを取得します。
永続的な接続を使用しているため、認証プロセスに注意する必要があります。参照 このリンク 必要に応じてそこに提供されているコードを微調整できます。
リクエストのIDを変更するには、FormsAuthentication_OnAuthenticateをglobal.asaxに追加する必要があります。私のアプリケーション用に書いたサンプルコードを次に示します。
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
//Let us set the Pricipal with our user specific details
e.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), _user.GetUserRoles(username));
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
お役に立てれば。
回答№2の場合は1
Signal-Rが変更できないことが判明SignalRは認証を行うことを想定していないため、IPrincipalに関連付けられていますが、アプリケーションから認証コンテキストを取得します。 @Shashankが指摘したように、これを行う正しい方法は、Formsまたはアプリケーションで使用するものを使用することであり、SignalRはこのコンテキストを取得します。
回答№3の場合は0
インターフェースを実装する IUserIdProvider
を使用して追加します
GlobalHost.Configuration.Resolver.Register(typeof(IUserIdProvider), () => provider.Object);
あなたはもっと読むことができます ここに.