在/ negotiate中对用户进行身份验证后,SignalR核心自定义身份验证-Context.User.Identity为null

时间:2019-03-08 10:05:05

标签: authentication asp.net-core-signalr

我为SignalR Core写了一个自定义身份验证。功能之一是匿名登录。如果是第一次用户连接,它将创建新用户。代码可以正常工作,但问题是在清除 / myhub / negotiate 并再次清除 Context.User.Identity 中的所有声明并且IsAuthenticated更改为false后,完成身份验证客户请求 / myhub / 。仅在此之后,才会清除 Context.User.Identity 中的声明。如果尝试发送 / myhub / negotiate 的请求,我尝试返回“失败”,但是如果我这样做,客户端将不会向 / myhub / 发送请求。

关于如何解决或解决此问题的任何想法?我的自定义身份验证工具正确吗?

这是我正在使用的所有类的代码:

public class CustomAuthRequirementHandler : AuthorizationHandler<CustomAuthRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomAuthRequirement requirement)
    {
        string name = context.User.Claims.Where(p => p.Type == ClaimTypes.NameIdentifier).Select(p => p.Value).SingleOrDefault();
        if (!context.User.Identity.IsAuthenticated)
            context.Fail();
        else
            context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

public class CustomAuthRequirement : IAuthorizationRequirement
{

}

public class MyAuthenticationHandler : AuthenticationHandler<MyOptions>
{
    public MyAuthenticationHandler(IOptionsMonitor<MyOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
    : base(options, logger, encoder, clock) { }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (Context.User.Identity != null && Context.User.Identity.IsAuthenticated) return await Task.FromResult(
                      AuthenticateResult.Success(
                         new AuthenticationTicket(
                             new ClaimsPrincipal(Options.Identity),
                             new AuthenticationProperties(),
                             this.Scheme.Name)));
        //if (Request.Path != "/myhub/") return await Task.FromResult(AuthenticateResult.Fail()); // only do authentication in /myhub/
        var u = CreateNewUser(); // connect to db create new user
        var claims = new List<Claim>() { };
        claims.Add(new Claim(ClaimTypes.Name, u.Id.ToString()));
        claims.Add(new Claim(ClaimTypes.NameIdentifier, u.Id.ToString()));
        Options.Identity = new ClaimsIdentity(claims, "Custom");
        var user = new ClaimsPrincipal(Options.Identity);
        Context.User = user;
        return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(user, new AuthenticationProperties(), this.Scheme.Name)));                        
    }

}

public class MyOptions : AuthenticationSchemeOptions
{
    public ClaimsIdentity Identity { get; set; }

    public MyOptions()
    {

    }
}

ConfigureServices中的配置代码

        services.AddSingleton<IAuthorizationHandler, CustomAuthRequirementHandler>();
        services.AddAuthorization(p =>
        {
            p.AddPolicy("MainPolicy", builder =>
            {
                builder.Requirements.Add(new CustomAuthRequirement());
                builder.AuthenticationSchemes = new List<string> { "MyScheme" };
            });
        });

        services.AddAuthentication(o =>
        {
            o.DefaultScheme = "MyScheme";
        }).AddScheme<MyOptions, MyAuthenticationHandler>("MyScheme", "MyScheme", p => { });            
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddSignalR();

配置代码

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSignalR(routes =>
        {
            routes.MapHub<Hubs.MainHub>("/main");
        });
        app.UseMvc();
    }

编辑:添加了客户端代码

    @page
@{
    ViewData["Title"] = "Home page";
}

<input type="button" onclick="anonLogin()" value="AnonLogin" />
<script src="~/@@aspnet/signalr/dist/browser/signalr.js"></script>
<script type="text/javascript">
    var connection;    

    function anonLogin() {
        var token = "anon";
        connection = new signalR.HubConnectionBuilder().withUrl("/main?anon=" + token).build();        

        connection.start().then(function () {
            console.log("Connection ok");

            console.log("Sending message....");
            connection.invoke("Test").catch(function (err) {
                return console.error("Error sending message: " + err.toString());
            });
        }).catch(function (err) {
            console.log("Connection error: " + err.toString());
            return console.error(err.toString());
        });
    }
</script>

1 个答案:

答案 0 :(得分:0)

我最终只是为/ myhub / negotiate的调用创建了一个虚假的身份声明,因为该调用并不重要,它只需要身份验证即可成功,以便可以转到/ myhub/。

var u = new DomainUser() { Id = -1 };
        var claims = new List<Claim>() { };
        claims.Add(new Claim(ClaimTypes.Name, u.Id.ToString()));
        claims.Add(new Claim(ClaimTypes.NameIdentifier, u.Id.ToString()));
        Options.Identity = new ClaimsIdentity(claims, "Custom");
        var user = new ClaimsPrincipal(Options.Identity);
        Context.User = user;
        return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(Context.User, new AuthenticationProperties(), this.Scheme.Name)));