我有.Net Core 2.1应用程序,并添加了JWT授权
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
...
});
如何记录访问具有[Authorize]
属性的操作的尝试?我想用这种方法https://stackoverflow.com/a/46963194/7137259并注入我的Logger,但我的Loggers使用实体数据库上下文,并且我不能将作用域Logger注入到IConfigureNamedOptions
。此外,未经授权时如何返回正常响应?
您可以在JwtBearerEvents中解析您的作用域服务,也可以在那里修改响应:
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
{
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
var svc = c.HttpContext.RequestServices.GetRequiredService<IMyService>();
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
c.Response.WriteAsync(c.Exception.ToString()).Wait();
return Task.CompletedTask;
}
};
});