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

.NET 6.0中JWT认证授权401 Unauthorized错误:自定义生成的Token无法被系统识别

Troubleshooting 401 Unauthorized with JWT in .NET 6

Let's break down the possible issues causing your 401 Unauthorized error when using the generated JWT, and walk through actionable solutions for each:

1. Insufficient SecurityKey Length (Most Likely Cause)

HMAC-SHA256 (the algorithm you're using) requires a minimum key length of 256 bits (32 characters). Your current SecurityKey in appsettings.json is "mysecretkeymysecretkey"—that's only 22 characters, which doesn't meet the requirement. This will silently fail token validation, leading to a 401.

Fix:
Update your SecurityKey to a string that's at least 32 characters long. For example:

"SecurityKey": "mySuperSecure32CharacterLongSecretKeyHere"

2. Verify Token Validation Parameters Match Token Creation

Double-check that the parameters used to validate the token match exactly what you used to create it:

  • Ensure the Issuer, Audience, and SecurityKey values in Program.cs's TokenValidationParameters are identical to those in JwtHelper (they should pull from the same TokenOptions section, which they do in your code—but confirm no typos or case mismatches).
  • Confirm the algorithm matches: You're using SecurityAlgorithms.HmacSha256Signature for signing, which aligns with the HMAC-SHA256 validation in your setup.
  • Check if the token is expired: Your AccessTokenExpiration is set to 500 minutes, which is long, but test with a freshly generated token to rule out expiration.

3. Ensure Correct Request Token Format

Make sure you're passing the token correctly in your request headers:

  • The token must be sent in the Authorization header with the format: Bearer <your-generated-token>
  • In Postman, go to the Headers tab, add a key Authorization, and set the value to Bearer [your-token] (replace [your-token] with the actual token string, no brackets).
  • Avoid typos like lowercase bearer (most frameworks are case-insensitive, but it's safer to use the standard Bearer).

4. Validate Token Structure with JWT Debugger

Use a tool like jwt.io to parse your generated token and verify:

  • The iss (issuer) and aud (audience) claims match your TokenOptions values.
  • The exp (expiration) timestamp is in the future.
  • All expected claims (like nameid, email, role) are present and correctly populated.

5. Add Debug Logs to Identify Validation Failures

To get concrete details on why validation is failing, add event handlers to your JWT bearer configuration in Program.cs:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        // ... your existing parameters ...
    };

    // Add these events to debug validation issues
    options.Events = new JwtBearerEvents
    {
        OnAuthenticationFailed = context =>
        {
            Console.WriteLine($"Authentication failed: {context.Exception.Message}");
            // If you're using a logging framework, replace Console.WriteLine with your logger
            return Task.CompletedTask;
        },
        OnTokenValidated = context =>
        {
            Console.WriteLine("Token validated successfully!");
            return Task.CompletedTask;
        }
    };
});

Run your app and check the console output when you make a request with the token—this will tell you exactly why validation is failing (e.g., "Invalid key", "Token expired", "Audience mismatch").

6. Confirm Middleware Order is Correct

Your current middleware order in Program.cs is correct, but double-check to ensure:

app.UseHttpsRedirection();
app.UseAuthentication(); // Must come BEFORE UseAuthorization
app.UseAuthorization();

If UseAuthorization comes before UseAuthentication, the app will try to authorize before authenticating, leading to 401.

7. Validate Autofac Dependency Injection

Ensure JwtHelper is correctly receiving the IConfiguration and TokenOptions:

  • Add a debug log in the JwtHelper constructor to confirm _tokenOptions is populated correctly:
    public JwtHelper(IConfiguration configuration)
    {
        Configuration = configuration;
        _tokenOptions = Configuration.GetSection("TokenOptions").Get<TokenOptions>();
        Console.WriteLine($"SecurityKey from config: {_tokenOptions.SecurityKey}");
        Console.WriteLine($"Issuer from config: {_tokenOptions.Issuer}");
    }
    

This will confirm that the helper is using the same values as your validation setup.


Start with the security key length fix first—it's the most probable cause here. If that doesn't resolve the issue, use the debug logs to narrow down the exact validation failure.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:52:37