Httpcontext用户声明始终为空

问题描述

我有一个.net core 3.0 api应用程序,并且在ConfigureServices部分中有以下代码

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbCustom(Configuration.GetConnectionString("mystr"));

        services.AddIdentity<UserClass,IdentityRole>(options =>
            {
                options.Password.requiredigit = false;
                options.Password.requiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.requiredUniqueChars = 0;
                options.Password.RequireNonAlphanumeric = false;
                options.Lockout.AllowedForNewUsers = false;
            })
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<DbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

        services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl = "/login";
                options.UserInteraction.logoutUrl = "/login";
                options.Endpoints.EnabletokenEndpoint = true;
                options.IssuerUri = "https://sistemaxyz.com";
            })
            .AddApiAuthorization<UserClass,DbContext>(options =>
            {
                options.Clients.Add(
                    new Client
                    {
                        ClientId = "cId",ClientName = "cName",Enabled = true,AllowedScopes = { "profile" },RequireClientSecret = false,UpdateAccesstokenClaimsOnRefresh = true,AllowAccesstokensViabrowser = true,AccesstokenLifetime = 24 * 60 * 60,AllowedGrantTypes = { GrantType.ResourceOwnerPassword }
                    });
            })
            .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
            .AddProfileService<CustomProfileService>()
            .AddDeveloperSigningCredential(true);

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllers().AddNewtonsoftJson(opt =>
        {
            opt.SerializerSettings.DateFormatString = "dd/MM/yyyy";
        });

        services.AddHttpContextAccessor();

        services.AddTransient<IUserService,UserService>();

        services.AddAutoMapper(typeof(EmpMapping).Assembly);

        services.AddMediatR(typeof(GetoneEmpQueryHandler).Assembly,typeof(InsertEmpresaCommandHandler).Assembly);

        services.AddCors(options =>
        {
            options.AddPolicy("method",policy =>
            {
                policy.AllowAnyOrigin();
                policy.AllowAnyMethod();
                policy.AllowAnyHeader();
            });
        });

        services.AddSpaStaticFiles(configuration => { configuration.RootPath = "path"; });

        services.Configure<CookiePolicyOptions>(options =>
        {
            services.AddHttpContextAccessor();
            services.TryAddSingleton<IHttpContextAccessor,HttpContextAccessor>();
        });
    }

UserService应该从当前用户检索2个UserClaims,但是它始终返回空。用户身份似乎也返回一个空的。 UserService类(我缺少什么?):

public class UserService : IUserService
{
    public UserService(IHttpContextAccessor httpContextAccessor)
    {
        var id = httpContextAccessor.HttpContext?.User?.Claims?.FirstOrDefault(c => c.Type == "sub")?.Value;
        UserId = id;

        var emp = httpContextAccessor.HttpContext?.User?.Claims?.FirstOrDefault(c => c.Type == "EmpId")?.Value;
        EmpId = !string.IsNullOrEmpty(emp)?(int?)int.Parse(emp):null;
    }

    public string UserId { get; }
    public int? EmpId { get; }
}

}

此处的解决方案:IHttpContextAccessor.HttpContext.User.Identity shows all null properties in CurrentUserService service

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)