【问题标题】:Authenticate SignalR from MVC Controller从 MVC 控制器验证 SignalR
【发布时间】:2015-11-01 17:45:40
【问题描述】:

我正在学习 ASP.NET Identity 和 SignalR 等。我能够使用 Identity 的自定义实现创建自己的身份验证系统。我现在正在尝试在调用覆盖的 OnConnected 之前向 SignalR 验证用户的身份。
用户通过 Cookie Authentication 验证后,[System.Web.Mvc.Authorize] 属性成功通过,而[Microsoft.AspNet.SignalR] 属性告诉我用户尚未通过身份验证。

//This is my Authorize method:
[HttpGet]
public ActionResult Authorize()
{
    AuthenticationManager.SignIn(new ClaimsIdentity(new ClaimsPrincipal(User).Claims.ToArray(), "Bearer"));
    return new EmptyResult();
}

//This is my CookieAuthenticationOptions
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider()
});

//On the Hub
public override Task OnConnected()
{
    string userName = Context.User.Identity.Name; //User is null?
}

我在这里缺少什么?我已经用谷歌搜索了一段时间,但我找不到任何东西,甚至不知道如何向 SignalR 进行身份验证。

【问题讨论】:

    标签: c# asp.net asp.net-mvc authentication


    【解决方案1】:

    您很可能在身份验证之前映射 SignalR,您必须在身份验证后映射 SignalR:

    public void Configuration(IAppBuilder app)
    {
    
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Home/Index")
            });
    
            //...
    
            app.MapSignalR();    
    }
    

    【讨论】:

    • 就是这样!在 Startup.cs 中,在 Configuration(IAppBuilder) 下,app.MapSignalR() 在 ConfigureAuth 之前。谢谢!现在可以使用了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多