首页 > 解决方案 > 登录时添加声明

问题描述

我在 .NET Core 2.2 中为新的身份验证而苦苦挣扎的日子我有:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = $"/api{CookieAuthenticationDefaults.LoginPath}";
                options.LogoutPath = $"/api{CookieAuthenticationDefaults.LogoutPath}";
                options.EventsType = typeof(MyEvents);
            });
        services.AddScoped<MyEvents>();
    }

    public class MyEvents : CookieAuthenticationEvents
    {
        public async override Task SignedIn(CookieSignedInContext context)
        {
            // do some checks
            // add cookie to CookieManager >> WORKS WELL
            // add claims to Principal >> NOT WORKING

            if (error) 
            { await context.HttpContext.SignOutAsync(scheme); context.Principal = null ; }
         }

        public async override Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            // idea here is to check if claims are already set, if not add them
            if (context.Principal.HasClaim(c => c.Type == ClaimTypes.NameIdentifier))
                return;

            // time consuming claims search
            // add claims here : WORKS but only for this instance
         }

问题

在 SignedIn 中添加声明绝对没有任何作用,当返回调用方法时,声明未设置。

在 ValidatePrincipal 中添加声明仅适用于当前的 [Authorize] 检查。每次我输入此方法时,都不再设置索赔。

我想避免搜索索赔的耗时过程。有没有更安全的方法可以为会话添加一次?

干杯,

标签: c#authenticationcookies.net-core

解决方案


推荐阅读