我有一个.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; }
}
}