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 核心中记录授权尝试
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
