.NET 6.0中JWT认证授权401 Unauthorized错误:自定义生成的Token无法被系统识别
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, andSecurityKeyvalues inProgram.cs'sTokenValidationParametersare identical to those inJwtHelper(they should pull from the sameTokenOptionssection, which they do in your code—but confirm no typos or case mismatches). - Confirm the algorithm matches: You're using
SecurityAlgorithms.HmacSha256Signaturefor signing, which aligns with the HMAC-SHA256 validation in your setup. - Check if the token is expired: Your
AccessTokenExpirationis 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
Authorizationheader with the format:Bearer <your-generated-token> - In Postman, go to the Headers tab, add a key
Authorization, and set the value toBearer [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 standardBearer).
4. Validate Token Structure with JWT Debugger
Use a tool like jwt.io to parse your generated token and verify:
- The
iss(issuer) andaud(audience) claims match yourTokenOptionsvalues. - 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
JwtHelperconstructor to confirm_tokenOptionsis 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

