Angular 17 +Net Core 6 использование JWT

доброе время суток Пытаюсь добавить в проект Angular + Net Core 6 - JWT. Все время выпадает ошибка 401 Вот код который добавил в Program.cs

//Jwt configuration starts here
var jwtIssuer = builder.Configuration.GetSection("Jwt:Issuer").Get<string>();
var jwtKey = builder.Configuration.GetSection("Jwt:Key").Get<string>();
var jwtAudience = builder.Configuration.GetSection("Jwt:Audience").Get<string>();
var env = builder.Environment;
builder.Services.AddControllers();
builder.Services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
 .AddJwtBearer(options =>
 {
     //options.Authority="https://localhost:8433"
     options.TokenValidationParameters = new TokenValidationParameters
     {
         ValidateIssuer = true,
         ValidateAudience = true,
         ValidateLifetime = true,
         ValidateIssuerSigningKey = true,
         ValidIssuer = jwtIssuer,
         ValidAudience = jwtAudience,
         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
     };
 });
//Jwt configuration ends here

Это организация самого токена

var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

var claims = new[]
{
    new Claim(JwtRegisteredClaimNames.Sub, HttpContext.User.Identity.Name),
    //new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress),
    //new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")),
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    new Claim("Role", "Admin")
};
var Sectoken = new JwtSecurityToken(_config["Jwt:Issuer"],
  _config["Jwt:Issuer"],
  claims: claims.Length > 0 ? claims : null,
  expires: DateTime.Now.AddMinutes(duration),
  signingCredentials: credentials);

var token = new JwtSecurityTokenHandler().WriteToken(Sectoken);

И в controller добален атрибут:

 [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
 [Route("api/[controller]")]
 [ApiController]

в Angular добавил Interceptor:

const token = sessionStorage.getItem('token');
if (token == null) {
  return next(req);
}

const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });
const clonedRequest = req.clone({ headers });

return next(clonedRequest);

Появляеться окно SignIn - не мое :-)

Появляеться окно SignIn - не мое :-)

Код ошибки

       Failed to load resource: the server responded with a status of 401 (Unauthorized)
...
core.mjs:6531 ERROR Error: Http failure response for http://localhost:8933/api/orgunits/getOrgUnitsAction: 401 Unauthorized
    at api.service.ts:74:29
    at Observable.init [as _subscribe] (throwError.js:5:51)
    at Observable._trySubscribe (Observable.js:37:25)
    at Observable.js:31:30
    at errorContext (errorContext.js:19:9)
    at Observable.subscribe (Observable.js:22:21)
    at catchError.js:14:31
    at OperatorSubscriber._error (OperatorSubscriber.js:23:21)
    at OperatorSubscriber.error (Subscriber.js:40:18)
    at OperatorSubscriber._error (Subscriber.js:64:30)


Ответы (0 шт):