繁体   English   中英

如何在 .net 核心中记录授权尝试

[英]How do I log authorization attempts in .net core

当我尝试访问授权属性下的方法时,我正在尝试写入日志。 基本上,我想记录一个人是否使用了无效令牌或过期令牌。 我正在使用 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))
        };

    });

有没有一种方法可以将一段代码添加到授权检查中,以记录授权尝试是否有效以及为什么无效?

您可以访问 JwtBearerEvents 对象,该对象定义了在处理不记名令牌时引发的许多事件。

验证失败
如果在请求处理期间抛出异常,则调用。 除非被抑制,否则在此事件之后将重新抛出异常。

OnChallenge 在将质询发送回调用方之前调用。

OnMessageReceived
在第一次收到协议消息时调用。

OnTokenValidated
在安全令牌通过验证并生成 ClaimsIdentity 后调用。

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents?view=aspnetcore-2.0

在 AddJwtBearer 初始化配置时,添加您要订阅的事件,

.AddJwtBearer(o =>
{
    o.Events = new JwtBearerEvents()
    {
        OnAuthenticationFailed = c =>
        {
            // do some logging or whatever...
        }

    };
});

查看源代码以了解何时可能引发事件,

https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs

不确定它是否已经在早期版本的 .NET (Core) 中实现,但我使用的是 .NET 6,我可以通过将日志级别设置为 Microsoft.AspNetCore 的Information来激活在 .NET 6 中实现的日志记录Microsoft.AspNetCore.Authentication类别。

例如在您的appsettings.json中:

 "Logging": {
    "LogLevel": {
      // ...
      "Microsoft.AspNetCore.Authentication": "Information"
    }
  }

这给了我一个过期令牌的以下日志(我正在使用带有模板的 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()

当然,如果您想限制更多,您可以在appsettings.json中使用Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler类别。 将此类的日志级别设置为Information非常重要,因为生成的 .NET 6 日志具有此日志级别。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM