[英]How do I log authorization attempts in .net core
I'm trying to write to a log when I person tries to access a method under an Authorize Attribute.当我尝试访问授权属性下的方法时,我正在尝试写入日志。 Basically, I want to log if a person uses an invalid token or an expired token.基本上,我想记录一个人是否使用了无效令牌或过期令牌。 I'm using basic Authentication for JWT我正在使用 JWT 的基本身份验证
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = jwtAudience,
ValidIssuer = jwtIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecurityKey))
};
});
Is there a way I can add a piece of code to the authorization check that logs if a authorization attempt was valid and why it wasn't?有没有一种方法可以将一段代码添加到授权检查中,以记录授权尝试是否有效以及为什么无效?
You have access to the JwtBearerEvents object, which defines a number of events that are raised as the bearer token is processed.您可以访问 JwtBearerEvents 对象,该对象定义了在处理不记名令牌时引发的许多事件。
OnAuthenticationFailed验证失败
Invoked if exceptions are thrown during request processing.如果在请求处理期间抛出异常,则调用。 The exceptions will be re-thrown after this event unless suppressed.除非被抑制,否则在此事件之后将重新抛出异常。
OnChallenge Invoked before a challenge is sent back to the caller. OnChallenge 在将质询发送回调用方之前调用。
OnMessageReceived OnMessageReceived
Invoked when a protocol message is first received.在第一次收到协议消息时调用。
OnTokenValidated OnTokenValidated
Invoked after the security token has passed validation and a ClaimsIdentity has been generated.在安全令牌通过验证并生成 ClaimsIdentity 后调用。
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents?view=aspnetcore-2.0 https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents?view=aspnetcore-2.0
When initialising the configuration at AddJwtBearer, add the events you'd like to subscribe to,在 AddJwtBearer 初始化配置时,添加您要订阅的事件,
.AddJwtBearer(o =>
{
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
// do some logging or whatever...
}
};
});
Have a look at the source to see when events might be raised,查看源代码以了解何时可能引发事件,
https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs
Not sure if it's already implemented in earlier versions of .NET (Core) but i'm using .NET 6 and i'm able to activate the logging implemented in .NET 6 by setting the loglevel to Information
for to the Microsoft.AspNetCore.Authentication
category.不确定它是否已经在早期版本的 .NET (Core) 中实现,但我使用的是 .NET 6,我可以通过将日志级别设置为 Microsoft.AspNetCore 的Information
来激活在 .NET 6 中实现的日志记录Microsoft.AspNetCore.Authentication
类别。
For example in your appsettings.json
:例如在您的appsettings.json
中:
"Logging": {
"LogLevel": {
// ...
"Microsoft.AspNetCore.Authentication": "Information"
}
}
This gave me the the following log for an expired token (i'm using log4net with a template):这给了我一个过期令牌的以下日志(我正在使用带有模板的 log4net):
INFO [Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler] - MESSAGE: Failed to validate the token.
Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: IDX10223: Lifetime validation failed. The token is expired. ValidTo: 'System.DateTime', Current time: 'System.DateTime'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateLifetime(Nullable`1 notBefore, Nullable`1 expires, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
Of course if you want to be more restrictive you could instead use the Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler
category in your appsettings.json
.当然,如果您想限制更多,您可以在appsettings.json
中使用Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler
类别。 It's just important to have the loglevel for this class set to Information
since the generated .NET 6 logs have this loglevel.将此类的日志级别设置为Information
非常重要,因为生成的 .NET 6 日志具有此日志级别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.