使用SignalR 2.X.X,Context.User.Identity.Name为null。怎么解决?

问题描述 投票:36回答:4

这让我疯了。

我正在使用最新的signalR版本(2.0.2)。这是我的集线器代码(OnConnected)

        public override Task OnConnected()
        {
            //User is null then Identity and Name too.
            Connections.Add(Context.User.Identity.Name, Context.ConnectionId);
            return base.OnConnected();
        }

这是我的Controller的登录方法:

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
              var user = await UnitOfWork.UserRepository.FindAsync(model.UserName,  model.Password);

                if (user != null)
                {
                    await SignInAsync(user, model.RememberMe);

                    return RedirectToLocal(returnUrl);
                }
            }

            TempData["ErrorMessage"] = Resources.InvalidUserNameOrPassword;

            // If we got this far, something failed, redisplay form
            return RedirectToAction("Index","Home");
        }

我发现有些人在OnDisconnected上遇到这个问题,我甚至都没有。

我正在使用MCV5模板。

你知道什么是错的吗?

asp.net-mvc authentication signalr signalr-hub owin
4个回答
93
投票

我找到了最终解决方案,这是我的OWIN启动类的代码:

        public void Configuration(IAppBuilder app)
        {
        app.MapSignalR();

        // Enable the application to use a cookie to store information for the signed i user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Index")
        });

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseMicrosoftAccountAuthentication(new MicrosoftProvider().GetAuthenticationOptions());
        app.UseTwitterAuthentication(new TwitterProvider().GetAuthenticationOptions());
        app.UseFacebookAuthentication(new FacebookProvider().GetAuthenticationOptions());
        app.UseGoogleAuthentication(new GoogleProvider().GetAuthenticationOptions());    
    }

让自己喝点咖啡,我想“在身份验证后映射SignalR怎么样,瞧!现在它的工作符合预期。

        public void Configuration(IAppBuilder app)
        {
        // Enable the application to use a cookie to store information for the signed i user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Home/Index")
        });

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseMicrosoftAccountAuthentication(new MicrosoftProvider().GetAuthenticationOptions());
        app.UseTwitterAuthentication(new TwitterProvider().GetAuthenticationOptions());
        app.UseFacebookAuthentication(new FacebookProvider().GetAuthenticationOptions());
        app.UseGoogleAuthentication(new GoogleProvider().GetAuthenticationOptions());

        app.MapSignalR();    
    }

5
投票

如果您在同一个项目中使用Web Api和SignalR,则必须在注册Web Api之前映射SignalR。

改变这个:

app.UseWebApi(GlobalConfiguration.Configuration);
app.MapSignalR();

对此:

app.MapSignalR();
app.UseWebApi(GlobalConfiguration.Configuration);

2
投票

只要确保认证。在启动app.MapSignalR()之前调用配置

我换了这个

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
        ConfigureAuth(app);



    }
}

对此

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.MapSignalR();


    }
}

拥抱..


2
投票

如果您将/signalr映射为“分支管道”,则需要执行此操作。一定要使用bp.UseCookieAuthentication而不是app

app.Map("/signalr", bp =>
{
   bp.UseCookieAuthentication(new CookieAuthenticationOptions
   {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/store/youRaccount/login")
   });

提示:我故意改变了外壳,所以当我在URL栏中看到youRaccount时,我知道它有效:-)


0
投票

.NET Core SignalR only

对于较新的.NET Core SignalR,完整说明解释了当使用websockets时,您需要从查询字符串中手动拉出accessToken。这很容易错过。

https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-2.2

基本上你调用AddAuthentication()的地方你需要添加AddJwtBearer()然后为OnMessageReceived处理程序设置一个处理程序。

在上面的代码链接中搜索“OnMessageReceived”。从某种意义上说,你甚至必须自己添加它,这有点粗糙 - 但这就是为什么它也很容易错过。

© www.soinside.com 2019 - 2024. All rights reserved.