信号核心自定义身份验证-Contection.user.Sidentity在用户进行身份验证 /协商后的身份无效



我为SignalR Core编写了自定义身份验证。功能之一是匿名登录。如果它是第一次使用用户连接,它将创建新用户。代码工作,但问题是清除/myHub/nongotiate 后完成的身份验证,并且在 context.user.user.indity 中的所有索赔再次清除,并在false时再次清除为false客户端请求/myHub/。只有此后, context.user.identity 中的索赔才清除。我试图返回失败,如果请求/myHub/nongotiate ,但是如果我这样做的话,客户不会将请求发送到/myHub/em>。

关于如何解决或解决此问题的任何想法?我的自定义身份验证实施是否正确?

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

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>

我最终创建了一个伪造的索赔,只是为了呼叫/myhub/谈判,因为此呼叫不重要,它只需要成功的身份验证,因此可以访问/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)));

相关内容

最新更新