我已将我的 Identity Server 项目升级到 Net Core 2,现在我无法调用 iProfileService 对象来添加自定义用户声明。它在 Net Core 1 中确实有效。
Startup.cs 配置服务函数
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IProfileService, M25ProfileService>();
//Load certificate
var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "m25id-cert.pfx"), "mypassword");
services.AddIdentityServer()
.AddSigningCredential(cert)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
//options.EnableTokenCleanup = true;
//options.TokenCleanupInterval = 30;
})
.AddProfileService<M25ProfileService>()
.AddAspNetIdentity<ApplicationUser>();
Run Code Online (Sandbox Code Playgroud)
M25ProfileService.cs
public class M25ProfileService : IProfileService
{
public M25ProfileService(UserManager<ApplicationUser> userManager)
{
_userManager …Run Code Online (Sandbox Code Playgroud) 我如何通过声明对用户进行身份验证,其中包含用户角色?
在Startup.cs:
services.AddAuthorization(options => {
options.AddPolicy("CanEdit", policy => policy.RequireClaim("CanEdit"));
});
Run Code Online (Sandbox Code Playgroud)
在登录控制器中我有:
private async ValueTask<JwtSecurityToken> GetJwtSecurityToken(ApplicationUser user){
//var totalClaims = new List<Claim>();
//var userRoles = await _userManager.GetRolesAsync(user);
//foreach (var role in userRoles) {
// var roleClaims = await _roleManager.GetClaimsAsync(await _roleManager.Roles.SingleAsync(r => r.Name.Equals(role)));
// totalClaims.AddRange(roleClaims);
//}
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};
return new JwtSecurityToken(
_configuration["Token:Issuer"],
_configuration["Token:Audience"],
//totalClaims,
claims
expires: DateTime.UtcNow.AddHours(12),
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:Key"])),
SecurityAlgorithms.HmacSha256)
);
}
Run Code Online (Sandbox Code Playgroud)
方法 …