Ничего не работает, я перепробовал все, чатгпт, документы. Думаю, что-то не так, но я не знаю, что!
Мой интерфейс работает развязно, даже когда я проверяю свой токен JWT jwt.io, вроде работает.
Вот логи промежуточного ПО, четко видно, что токен попадает на бэкенд:
Twyt.Twyt.Api.Middleware.RequestLoggingMiddleware: Information: Handling request: GET /api/Post/user/82d3f35b-aa00-453b-80f5-2c06f2063e60
Twyt.Twyt.Api.Middleware.RequestLoggingMiddleware: Information: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI4MmQzZjM1Yi1hYTAwLTQ1M2ItODBmNS0yYzA2ZjIwNjNlNjAiLCJqdGkiOiJjYzYwZWNlMi0wZDE0LTQ3NWEtOTcxOC00NWYwMzhiM2VhZmIiLCJleHAiOjE3MjY0MTc1NDksImlzcyI6IlR3eXQiLCJhdWQiOiJUd3l0In0.UN8rtNhp6HI7Ut6ovUOTYBFmYHneHHbN8XblZRZ3PlU
Program: Warning: Token is null or empty
Loaded Assembly '/usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Diagnostics.StackTrace.dll'
Loading module /usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Diagnostics.StackTrace.dll in application domain 1:clrhost
Pdb file for assembly /usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Diagnostics.StackTrace.dll was not found or failed to read
Loaded Assembly '/usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Reflection.Metadata.dll'
Loading module /usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Reflection.Metadata.dll in application domain 1:clrhost
Pdb file for assembly /usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Reflection.Metadata.dll was not found or failed to read
Loaded Assembly '/usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Collections.Immutable.dll'
Loading module /usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Collections.Immutable.dll in application domain 1:clrhost
Pdb file for assembly /usr/local/share/dotnet/shared/Microsoft.NETCore.App/8.0.8/System.Collections.Immutable.dll was not found or failed to read
Program: Error: Authentication failed: Microsoft.IdentityModel.Tokens.SecurityTokenMalformedException: IDX14100: JWT is not well formed, there are no dots (.).
The token needs to be in JWS or JWE Compact Serialization Format. (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'.
---> System.MissingMethodException: Method not found: 'Byte[] Microsoft.IdentityModel.Tokens.Base64UrlEncoder.UnsafeDecode(System.ReadOnlyMemory`1)'.
at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken.ReadToken(String encodedJson)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebToken..ctor(String jwtEncodedString)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.ReadToken(String token, TokenValidationParameters validationParameters)
--- End of inner exception stack trace ---
Program: Warning: OnChallenge error: invalid_token
Twyt.Twyt.Api.Middleware.RequestLoggingMiddleware: Information: Finished handling request. Status code: 401
Twyt.Twyt.Api.Middleware.RequestLoggingMiddleware: Warning: Unauthorized access attempt: GET /api/Post/user/82d3f35b-aa00-453b-80f5-2c06f2063e60
Token Program.cs:
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
var key = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key is not configured"));
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"] ?? throw new InvalidOperationException("JWT Issuer is not configured"),
ValidAudience = builder.Configuration["Jwt:Audience"] ?? throw new InvalidOperationException("JWT Audience is not configured"),
IssuerSigningKey = new SymmetricSecurityKey(key)
};
options.IncludeErrorDetails = true;
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
var logger = context.HttpContext.RequestServices.GetRequiredService();
logger.LogError("Authentication failed: {Exception}", context.Exception.ToString());
return Task.CompletedTask;
},
OnChallenge = context =>
{
var logger = context.HttpContext.RequestServices.GetRequiredService();
logger.LogWarning("OnChallenge error: {0}", context.Error);
return Task.CompletedTask;
},
OnMessageReceived = context =>
{
var logger = context.HttpContext.RequestServices.GetRequiredService();
var token = context.Token;
if (string.IsNullOrEmpty(token))
{
logger.LogWarning("Token is null or empty");
return Task.CompletedTask;
}
// Log the raw token for debugging
logger.LogInformation("Token received: {Token}", token);
return Task.CompletedTask;
}
};
});
builder.Services.AddAuthorization();
А это функцияgenerateToken, как вы можете видеть, она использует переменные из appsettings.json:
public async Task GenerateJwtToken(User user)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserId.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
_configuration["Jwt:Issuer"],
_configuration["Jwt:Audience"],
claims,
expires: DateTime.Now.AddHours(2),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Подробнее здесь: https://stackoverflow.com/questions/789 ... s-included
401 после добавления [authorize] к моей конечной точке, включая журналы ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение