c# - 从 MVC Controller 验证 SignalR

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

我正在学习 ASP.NET Identity 和 SignalR 等。我能够使用 Identity 的自定义实现创建自己的身份验证系统。我现在正在尝试在调用覆盖的 OnConnected 之前向 SignalR 验证用户身份。
用户使用 Cookie 身份验证获得身份验证后,[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 进行身份验证。

最佳答案

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

public void Configuration(IAppBuilder app)
{

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

        //...

        app.MapSignalR();    
}

关于c# - 从 MVC Controller 验证 SignalR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465180/

相关文章:

jquery - 流程图条形宽度

asp.net - App_Start 中缺少 WebApiConfig.cs。我可以使用 Startup.cs 吗?

asp.net - asp 上的 jQuery 单击事件 :button

c# - 现在是在 ASP.NET MVC 中使用多线程的好时机吗?它是如何实现的?

c# - 从另一个列表对象创建对象列表 LINQ Lambda

c# - ASP.NET Core MVC 应用程序发布时的奇怪行为

c# - UWP 错误?绑定(bind)到某些嵌套的 DependencyProperty 将不起作用

c# - 寻找一种更快的算法来计算文档数据库中动态标签云的标签/关键字/标签

c# - MVC4 webapi 中的反序列化/模型绑定(bind)不适用于数组

asp.net - 将 JSON 发布到 Controller