如何在Signalr hub获取Owin身份

时间:2018-01-08 16:23:47

标签: asp.net-mvc authentication signalr owin

我使用带有Owin外部身份验证(steam)的SignalR在ASP.NET MVC中编写了一个应用程序。

问题是我无法在SignalR集线器内获取任何身份信息。 Identity.Name返回空字符串,Identity.Claims为空。

Startup.cs

public class Startup
{
  public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Index"),
            AuthenticationMode = AuthenticationMode.Active

        });

      app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
     app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        app.UseSteamAuthentication("API KEY");
    }
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.MapSignalR();
    }
}

在SteamCallBack中

  

authenticateResult?.Identity.Claims

不为空,它返回Steam提供的正确的Identity.Name。

 public async Task<ActionResult> SteamCallback()
    {
        ....

        var authenticateResult =
               await HttpContext.GetOwinContext().Authentication.AuthenticateAsync("ExternalCookie");
        var firstOrDefault = authenticateResult?.Identity.Claims.FirstOrDefault(claim => claim.Issuer == "Steam" && claim.Type.Contains("nameidentifier"));

     ...
    }

Inside Hub所有以下内容均为null / empty

  

var z = Context.User.Identity.Name;

     

var b = Context.User.Identity.AuthenticationType;

     

var x =((ClaimsIdentity)Context.User.Identity).Claims.ToList();

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。我忘了使用IAuthenticationManager.SignIn方法登录用户。

使用该方法的示例:

var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
{
    AllowRefresh = true,
    IsPersistent = true,
    ExpiresUtc = DateTime.UtcNow.AddDays(7)
}, identity);