How do I log authorization attempts in .net core(如何在 .net 核心中记录授权尝试)
问题描述
当我尝试访问授权属性下的方法时,我正在尝试写入日志.基本上,我想记录一个人是否使用了无效令牌或过期令牌.我正在使用 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
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.
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.jwtbearer.jwtbearerevents?view=aspnetcore-2.0
在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,
https://github.com/aspnet/Security/blob/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs
这篇关于如何在 .net 核心中记录授权尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 .net 核心中记录授权尝试


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01