[英]How to use keycloak in .net core 5.0 with AspNet Core Identity?
我在我的项目中使用带有 CQRS 的 aspnet core 5.0 webapi,并且已经有了 jwt 实现。 不使用来自 aspnet 核心的角色管理,而是为 aspnet 用户表角色字段手动添加,并且到处都在使用。 在互联网上,我找不到任何文章来为现有的身份验证和授权实现 keycloak。 我的观点是现在用户使用他们的电子邮件+密码登录,想法不适合所有人,但对于他们已经存储在 keycloak 中的一些用户,或者对于我们将存储在那里的一些用户,也使用 keycloak 为我们的应用程序提供选项登录。
场景一:
我在我的数据库和 keycloak 中都有 admin@gmail.com 并且它们都是管理员角色,我需要授予两者的访问权限才能登录我的应用程序,第一个场景已经工作需要首先实现第二个场景。
仅找到实现安全应用程序的这篇文章(因为我们已经拥有并且不尝试替换而是扩展)
我的 jwt 配置如下所示:
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services,
IConfiguration configuration)
{
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(configuration.GetSection("AppSettings:Token").Value));
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateAudience = false,
ValidateIssuer = false,
ClockSkew = TimeSpan.Zero
};
opt.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
return services;
}
我的 jwt 服务看起来像:
public JwtGenerator(IConfiguration config)
{
_key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetSection("AppSettings:Token").Value));
}
public string CreateToken(User user)
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id),
new(ClaimTypes.Email, user.Email),
new(ClaimTypes.Name, user.UserName),
new(ClaimTypes.Role, user.Role.ToString("G").ToLower())
};
var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddMinutes(15),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
我的登录方法如下所示:
public async Task<GetToken> Handle(LoginCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
throw new BadRequestException("User not found");
UserManagement.ForbiddenForLoginUser(user);
var result = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false);
if (result.Succeeded)
{
user.IsRoleChanged = false;
RefreshToken refreshToken = new RefreshToken
{
Name = _jwtGenerator.GenerateRefreshToken(),
DeviceName = $"{user.UserName}---{_jwtGenerator.GenerateRefreshToken()}",
User = user,
Expiration = DateTime.UtcNow.AddHours(4)
};
await _context.RefreshTokens.AddAsync(refreshToken, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
return new GetToken(_jwtGenerator.CreateToken(user),refreshToken.Name);
}
throw new BadRequestException("Bad credentials");
}
我的授权处理程序:
public static IServiceCollection AddCustomMvc(this IServiceCollection services)
{
services.AddMvc(opt =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
opt.Filters.Add(new AuthorizeFilter(policy));
// Build the intermediate service provider
opt.Filters.Add<CustomAuthorizationAttribute>();
}).AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<CreateProjectCommand>());
return services;
}
除了我目前的方法之外,实现 keycloak authentiaction+authorization 的最佳实践是什么,并让用户使用两种场景登录,正常登录和 keycloak 登录。
PS Ui 是不同的,我们使用 angular 这个只是后端的 webapi。
由于您的登录方法返回一个 jwt,您可以通过链接.AddJwtBearer()
来配置多个不记名令牌,一个用于您的正常登录,另一个用于 keycloak。
这是一个可以解决您的问题的问题的链接: 使用多个 jwt 承载身份验证。
钥匙斗篷配置:
您可以使用jwt.io上的调试器来检查您的令牌是否正确。 结果应如下所示:
{
"exp": 1627565901,
"iat": 1627564101,
"jti": "a99ccef1-afa9-4a62-965b-15e8d33de7de",
// [...]
// roles nested in realm_access :(
"realm_access": {
"roles": [
"offline_access",
"uma_authorization",
"Admin"
]
},
// [...]
// your mapped roles in your custom claim
"roles": [
"offline_access",
"uma_authorization",
"Admin"
]
// [...]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.