如何在.net Core中记录授权尝试 [英] How do I log authorization attempts in .net core
问题描述
当我尝试访问授权"属性下的方法时,我正在尝试写入日志.基本上,我想记录一个人是否使用了无效的令牌或过期的令牌.我正在对JWT使用基本身份验证
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
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?
推荐答案
您可以访问JwtBearerEvents对象,该对象定义了在处理承载令牌时引发的许多事件.
You have access to the JwtBearerEvents object, which defines a number of events that are raised as the bearer token is processed.
OnAuthenticationFailed
在请求处理期间引发异常时调用.除非受到抑制,否则此事件发生后将重新抛出异常.
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.
OnMessageReceived
首次接收到协议消息时调用.
OnMessageReceived
Invoked when a protocol message is first received.
OnTokenValidated
在安全令牌通过验证并已生成ClaimsIdentity后调用.
OnTokenValidated
Invoked after the security token has passed validation and a ClaimsIdentity has been generated.
在AddJwtBearer上初始化配置时,添加您要订阅的事件,
When initialising the configuration at AddJwtBearer, add the events you'd like to subscribe to,
.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,
这篇关于如何在.net Core中记录授权尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!