我想记录对我的 .netcore webapi 的所有调用的统计信息。
为此,我添加了一个 IAsyncActionFilter
,它会处理所有操作。
但我还启用了 Jwt Bearer 身份验证,并在我的 Controller 上使用 AuthorizeAttribute
来限制访问。当访问被拒绝时,将不会命中操作过滤器。
添加一些自定义日志记录 (statsd) 以进行一般身份验证和特定失败的最佳方法是什么?
public void ConfigureServices(IServiceCollection services)
{
....
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// base-address of your identityserver
options.Authority = Configuration["Authority"]; ;
// name of the API resource
options.Audience = "myAudience";
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseAuthentication();
...
}
我注意到 JwtBearerOptions
有 JwtBearerEvents 事件
,但我无法让它工作。
编辑:看起来我在没有 token 的情况下访问 api,JWT Auth 处理程序返回 AuthenticateResult.NoResult() 而不调用 Events.AuthenticationFailed
编辑 2:非常令人沮丧。看起来正确的登录位置应该在 Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter
中,但是当您使用 [Authorize]
时,它会自动添加并且无法覆盖,删除或替换?
最佳答案
JwtBearerOptions.cs 类公开了一个 JwtBearerEvents 参数,您可以在其中像这样声明您的事件
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// base-address of your identityserver
options.Authority = Configuration["Authority"]; ;
// name of the API resource
options.Audience = "myAudience";
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
//Log failed authentications
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
//Log successful authentications
return Task.CompletedTask;
}
};
});
关于c# - 如何使用 OWIN Jwt Bearer Authentication 记录认证结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538601/