我想记录对我的.netcore webapi的所有调用的统计信息。
为此,我已经添加了一个IAsyncActionFilter,它可以处理所有的操作。
但是,我还启用了Jwt Bearer身份验证,并且正在使用控制器上的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 Events,但我不能让它工作。
编辑:看起来我在没有令牌的情况下访问api,JWT处理程序不调用Events.AuthenticationFailed就返回AuthenticateResult.NoResult()
编辑2:非常令人沮丧。看起来正确的日志位置将在Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter中,但这是在使用[Authorize]时自动添加的,并且不可能覆盖、删除或替换?
发布于 2018-01-31 19:47:59
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;
}
};
});发布于 2018-01-31 16:43:04
我没有任何经验的Jwt比勒认证-但我们有类似的情况。我们最终得到了一个新的BaseController,在这里我们能够记录基本的用户信息并区分[AllowAnonymous]和[Authorize]。
public class NewBaseController : Controller
{
protected UserManager<MyUser> UserManager;
protected MyUser CurrentUser;
protected ILogger Logger;
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
UserManager = context.HttpContext.RequestServices.GetService<UserManager<MyUser>>();
var loggerFactory = context.HttpContext.RequestServices.GetService<ILoggerFactory>();
Logger = loggerFactory.CreateLogger(GetType());
// Check if Action is annotated with [AllowAnonymous]
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
var anonymousAllowed = controllerActionDescriptor.MethodInfo
.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
if (!anonymousAllowed)
{
ApplicationUser = UserManager.GetUserAsync(User).Result;
if (ApplicationUser == null)
// do some stuff
Logger.LogInformation("User is {UserId}", CurrentUser.Id);
}
else
{
Logger.LogInformation("User is {User}", anonymous);
}
}
}奖励:每个从这个基础派生的控制器都有一个UserManager、ILogger和CurrentUser的实例。
希望这接近你想要的.
https://stackoverflow.com/questions/48538601
复制相似问题