Сначала определяю имя схемы:
Код: Выделить всё
const string bearerJwtWrite = "JwtWrite";
Код: Выделить всё
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{ ... }
.AddJwtBearer(bearerJwtWrite, options =>
{
options.Authority = builder.Configuration["Jwt:Write:Issuer"];
options.Audience = builder.Configuration["Jwt:Write:Audience"];
//options.Challenge = bearerJwtWrite;
options.TokenValidationParameters = new TokenValidationParameters
Код: Выделить всё
OnTokenValidated = context =>
{
// Add custom claims to the principal if the token is valid
var claims = new[]
{
new Claim(
ClaimTypes.NameIdentifier,
context.Scheme.Name,
ClaimValueTypes.String, context.Options.ClaimsIssuer),
new Claim(ClaimTypes.Role, "Claim_AdminPrivilege_API_jwt_Write")
};
context.Principal = new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Scheme.Name));
return Task.CompletedTask;
},
Политика определяется так:
Код: Выделить всё
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Role_AdminPrivilege_API_jwt_Write", p => {
// Add the authentication scheme for certificate
p.AuthenticationSchemes.Add(bearerJwtWrite);
//p.RequireAssertion(context => true);
p.RequireClaim(ClaimTypes.Role, "Claim_AdminPrivilege_API_jwt_Write");
});
});
Код: Выделить всё
[Authorize(AuthenticationSchemes = "JwtWrite")]
[Authorize(Policy = "Role_AdminPrivilege_API_jwt_Write")]
[HttpPost("CreateEndpointAdminJwt")]
public async Task CreateEndpointAdminJwt([FromBody]MyModel model)
Подробнее здесь: https://stackoverflow.com/questions/792 ... ler-method
Мобильная версия