You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core授权问题:携带JWT Bearer令牌持续返回403错误

Hey there, let's dig into that 403 issue you're facing with JWT authorization. From the snippet you shared of your TokenManagement.cs, here are some common pitfalls to troubleshoot first:

Common Causes for JWT 403 Unauthorized Errors

1. Mismatched Claim Validation Rules

You mentioned adding a custom claim ("cla..."—looks like it got truncated). If your API’s authorization policies expect specific claim names/values (like roles or permissions) that don’t exactly match what’s in your token, the request will get blocked.

For example:

  • If your API uses [Authorize(Roles = "Admin")] but your token uses a custom claim name like "user_role" instead of the standard ClaimTypes.Role, the role check will fail.
  • Double-check your API’s authorization policy setup to ensure claim names, types, and values align perfectly between your token generator and the API validator.

2. Signing Key/Algorithm Mismatch

This is one of the most frequent culprits. If the secret key or signing algorithm you use to generate the token doesn’t match what your API uses to validate it, the token will be rejected as invalid.

Check your TokenManagement.cs signing logic:

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

Then compare it to your API’s validation setup (in Program.cs/Startup.cs):

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"])),
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidateAudience = true,
            ValidAudience = builder.Configuration["Jwt:Audience"],
            // Other parameters...
        };
    });

Make sure the SecretKey, Issuer, Audience, and signing algorithm (like HmacSha256) are identical on both sides. Also, ensure your secret key is long enough—HmacSha256 requires at least a 256-bit (32-character) key.

3. Expired or Invalid Standard Claims

JWT tokens rely on standard claims like exp (expiry), iss (issuer), and aud (audience) for validation. If:

  • Your token is past its expiry time (check the exp claim)
  • The iss/aud values don’t match what your API is configured to accept
  • You forgot to set these claims when generating the token

Your API will reject the request with a 403. Use a JWT parser (you can write a quick helper method or use a local tool) to inspect your token’s full claim set and verify these values.

4. Misconfigured Authorization Policies

If you’re using custom authorization policies in your API, ensure they’re correctly tied to your token’s claims. For example:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("RequireAdminAccess", policy =>
        policy.RequireClaim("Permission", "ManageUsers"));
});

If your token doesn’t include the exact claim "Permission": "ManageUsers", any endpoint using [Authorize(Policy = "RequireAdminAccess")] will return 403.

5. Incorrect Request Header Format

Double-check that your API request’s Authorization header follows the exact format: Bearer <your-token> (note the space after "Bearer"). Extra spaces, line breaks, or typos here can cause the token to be unparseable, leading to a 403 even if the token itself is valid.

Bonus: Middleware Ordering

Ensure your API’s middleware pipeline has authentication and authorization in the correct order:

app.UseAuthentication(); // Must come first
app.UseAuthorization();

If these are reversed or missing entirely, your JWT validation won’t run, and requests will be blocked.

If you can share the full token generation code (including how you set issuer, audience, and expiry) and your API’s authorization configuration, we can narrow this down even further!

内容的提问来源于stack exchange,提问作者Nelladel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:41:41