如何解决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; }
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。