我有一个客户端(Postman)和2个公共API(ImagesService和AdministrationService)
ImagesService和AdministrationService有一些带授权的操作
[Authorize(Policy = "Administrator")]
UsersService是用于验证在其他服务上收到的令牌是否有效的服务。
当客户端调用DeleteUser操作时,我希望AdministrationServices自动调用UserService并验证令牌。
UsersService.Startup.cs
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Core.Settings.Apis.User.Name,
ValidAudience = Core.Settings.Apis.User.Name,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Core.Settings.Apis.User.Secret)),
RequireSignedTokens = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("Administrator", policy => policy.RequireClaim("Administrator", "Administrator"));
});
UsersService.UsersController.cs
[HttpGet]
public IActionResult Login(string nick, string password)
{
var claims = new List<System.Security.Claims.Claim> { new System.Security.Claims.Claim("Administrator", "Administrator" )};
var token = new JwtSecurityToken
(
issuer: Core.Settings.Apis.User.Name,
audience: Core.Settings.Apis.User.Name,
claims: claims,
expires: DateTime.Now.AddHours(1)
);
var tokenHandler = new JwtSecurityTokenHandler().WriteToken(token);
return Ok(tokenHandler);
}
AdministrationService.ManageUsersController.cs
[HttpDelete]
[Authorize(Policy = "Administrator")]
public IActionResult DeleteUser(UserViewModel user)
{
// ...
}