简体   繁体   English

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

[英]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.

相关问题 如何使用.NET Core配置Elmah以登录到SQL? - How do I configure Elmah with .NET Core to log to SQL? 如何在 ASP.net 核心集成测试中获得授权(我非常接近) - How do I get Authorization working in ASP.net core integration testing (I'm very close) 如何在 ASP.NET Core 中发送带有 HTTP 基本授权的 HTTP POST? - How do I send an HTTP POST with HTTP Basic Authorization in ASP.NET Core? 如何为授权挑战设置两个不同的登录路径? (ASP.NET Core Razor 页面) - How do I set two different login paths for authorization challenge? (ASP.NET Core Razor Pages) 如何在 .Net 核心 Web API 中进行 Azure AD 组授权? - How to do Azure AD groups authorization in .Net core web API? 如何在 .net core 2.0 中进行简单的标头授权? - How to do simple header authorization in .net core 2.0? 如何在 .net 核心应用程序中进行基于组的授权? - How to do authorization based on groups in .net core app? 如何在ASP Core 2中建立基于角色的自定义授权? - How do I build a custom role based authorization in ASP Core 2? 如何在没有登录的情况下针对ASP.NET Core应用程序中的Active Directory组进行身份验证? - How do I authenticate against an Active Directory group in ASP.NET Core application without log in? Web API [Net.Core]上的授权失败时登录数据库 - Log to database when authorization fail on Web API [Net.Core]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM