WWW-Authenticate Bearer error="invalid_token", 无描述

问题描述 投票:0回答:0

我有一个测试 .NET 7 web api,我用它来测试动作过滤器属性的类库。我的目标是能够使用 Postman 更改声明以测试路由上的操作过滤器属性。所以,实际的安全是没有价值的。但是,为了让 Postman 的声明进入

_httpContextAccessor.HttpContext.User.Claims
,我试图在 Postman 预请求脚本中生成一个 JWT 令牌。

我的预请求脚本是:

// Set up the claims for the JWT token
var claims = { 
    "name": "john doe",
};

// Set up the JWT token options
var header = {
  "alg": "HS256",
  "typ": "JWT"
};

// Encode the header and payload as base64 strings
var encodedHeaders = btoa(JSON.stringify(header));
var encodedPlayload = btoa(JSON.stringify(claims));

// Create the token string by concatenating the encoded header, encoded claims, and signature
var signature = CryptoJS.HmacSHA256(`${encodedHeaders}.${encodedPlayload}`, "this_secret_doesnt_matter");
var encodedSignature = btoa(signature);

var token = `${encodedHeaders}.${encodedPlayload}.${encodedSignature}`;

// Save the token to the environment variable
pm.environment.set('jwt_token', token);

在测试 web api 中,Program.cs 看起来像:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.IncludeErrorDetails = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = false,
        ValidateIssuer = false,
        ValidateAudience = false,
        ClockSkew = TimeSpan.Zero
    };
});

builder.Services.AddHttpContextAccessor();

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAzureAppConfiguration();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

我已经安装了这两个 nuget 包:

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • System.IdentityModel.Tokens.Jwt

但是,每次我调用 [Authorize] 路由时,我都会收到 401 Unauthorized 和 WWW-Authenticate Bearer error="invalid_token",在标头中。

authentication jwt authorization bearer-token .net-7.0
© www.soinside.com 2019 - 2024. All rights reserved.