【问题标题】:How to get Owin identity in Signalr hub如何在 Signalr hub 中获取 Owin 身份
【发布时间】:2018-06-17 15:54:49
【问题描述】:

我有一个用 ASP.NET MVC 编写的应用程序,使用 SignalR 和 Owin 外部身份验证(Steam)。

问题是我无法在 SignalR hub 内获取任何身份信息。 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"));

     ...
    }

在 Hub 内部,以下所有内容均为空/空

var z = Context.User.Identity.Name;

var b = Context.User.Identity.AuthenticationType;

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

【问题讨论】:

    标签: asp.net-mvc authentication signalr owin


    【解决方案1】:

    我解决了我的问题。我忘记使用 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);
    

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 2016-03-08
      • 2021-03-26
      • 2015-02-02
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多