I implement an example from a matanite ( https://metanit.com/sharp/aspnet5/23.7.php ) where I generate a JWT token. But when I put the authorization attribute with the role of Admin, it gives an error in the browser 404 (Not Found). If I remove the role check and leave only the authorization attribute, then everything works.

Back-end code

public class AuthOptions { public const string ISSUER = "MyAuthServer"; // издатель токена public const string AUDIENCE = "http://localhost:51489/"; // потребитель токена const string KEY = "mysupersecret_secretkey!123"; // ключ для шифрации public const int LIFETIME = 60; // время жизни токена - 1 минута public static SymmetricSecurityKey GetSymmetricSecurityKey() { return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(KEY)); } } [HttpPost] [AllowAnonymous] [Route("login")] public async Task Login([FromBody]LoginViewModel model) { var identity = await GetIdentity(model.Email, model.Password); if (identity == null) { Response.StatusCode = 400; await Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; // создаем JWT-токен var jwt = new JwtSecurityToken( issuer: AuthOptions.ISSUER, audience: AuthOptions.AUDIENCE, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)), signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name, }; // сериализация ответа Response.ContentType = "application/json"; await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); return; } private async Task<ClaimsIdentity> GetIdentity(string username, string password) { var user = _db.User.FirstOrDefault(x => x.Email == username); if (user != null) { var checkPass = _userManager.CheckPasswordAsync(user, password); if (!checkPass.Result) return null; var userRoles = await _userManager.GetRolesAsync(user); string role = userRoles[0]; var claims = new List<Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email), new Claim(ClaimsIdentity.DefaultRoleClaimType, role) }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); return claimsIdentity; } // если пользователя не найдено return null; } 

Well, the startup class.

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = AuthOptions.ISSUER, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = AuthOptions.AUDIENCE, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); 

The only difference is that I get the role from the real AspNet table. In the example of methanite, they were stored in the object. Well, I do not think that this is the problem, that there is something there at the time of the new Claim in the GetIdentity method that places the role of "Admin" as a string value.

Well, just in case I load the token at the front (AngularJS)

 $http.defaults.headers.common['Authorization'] = 'Bearer ' + response.data.access_token; 

It seems there is nothing difficult ... And here is the controller to which I hang attributes. With verification Admin writes that he did not find api

  [HttpGet] [Route("logout")] [Authorize(Roles = "Admin")] public async Task<string> Logout() 

This is how it works.

 [HttpGet] [Route("logout")] [Authorize] public async Task<string> Logout() 

    0