問題描述
當(dāng)我嘗試訪問授權(quán)屬性下的方法時,我正在嘗試寫入日志.基本上,我想記錄一個人是否使用了無效令牌或過期令牌.我正在使用 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))
};
});
有沒有辦法我可以在授權(quán)檢查中添加一段代碼,以記錄授權(quán)嘗試是否有效以及為什么無效?
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 對象,該對象定義了在處理不記名令牌時引發(fā)的許多事件.
You have access to the JwtBearerEvents object, which defines a number of events that are raised as the bearer token is processed.
驗證失敗
如果在請求處理期間拋出異常,則調(diào)用.除非被抑制,否則異常將在此事件之后重新拋出.
OnAuthenticationFailed
Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.
挑戰(zhàn)在將質(zhì)詢發(fā)送回調(diào)用方之前調(diào)用.
OnChallenge Invoked before a challenge is sent back to the caller.
OnMessageReceived
在第一次收到協(xié)議消息時調(diào)用.
OnMessageReceived
Invoked when a protocol message is first received.
OnTokenValidated
在安全令牌通過驗證并生成 ClaimsIdentity 后調(diào)用.
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...
}
};
});
查看源代碼以了解何時可能引發(fā)事件,
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
這篇關(guān)于如何在 .net 核心中記錄授權(quán)嘗試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!