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

问题描述 投票:0回答:1

我为SignalR Core编写了一个自定义身份验证。其中一个功能是匿名登录。如果是第一次用户连接,它将创建新用户。代码工作但问题是在清除/ myhub / negotiate之后完成的身份验证,并且当客户端请求/ myhub /时,再次清除Context.User.Identity中的所有声明并且IsAuthenticated变为false。只有在此之后,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>
authentication asp.net-core-signalr
1个回答
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)));
© www.soinside.com 2019 - 2024. All rights reserved.