如何使用 OWIN Jwt Bearer 身份验证记录身份验证结果

Ewa*_*wan 5 c# jwt owin asp.net-core-mvc .net-core

我想记录对我的 .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();
...
}
Run Code Online (Sandbox Code Playgroud)

我注意到JwtBearerOptions有,JwtBearerEvents Events但我不能让它工作。

编辑:看起来我在访问 api 时根本没有令牌,JWT Auth 处理程序返回 AuthenticateResult.NoResult() 而不调用 Events.AuthenticationFailed

https://github.com/aspnet/Security/blob/ba1eb281d135400436c52c17edc71307bc038ec0/src/Microsoft.AspNetCore.Authentication.JwtBearer/JwtBearerHandler.cs#L63-L83

编辑2:非常令人沮丧。看起来应该是正确的登录位置Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter但是这是在您使用时自动添加的[Authorize]并且无法覆盖、删除或替换?

Mar*_*und 7

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;
            }
        };

    });
Run Code Online (Sandbox Code Playgroud)


Jos*_*hit 0

我\xc2\xb4t没有任何Jwt承载身份验证的经验 - 但我们\xc2\xb4ve有类似的情况。我们\xc2\xb4ve最终得到了一个新的BaseController,我们\xc2\xb4能够在其中记录基本用户信息并区分[AllowAnonymous][Authorize]

\n\n
public class NewBaseController : Controller\n{\n    protected UserManager<MyUser> UserManager;\n    protected MyUser CurrentUser;\n    protected ILogger Logger;\n\n    public override void OnActionExecuting(ActionExecutingContext context)\n    {\n        base.OnActionExecuting(context);\n\n        UserManager = context.HttpContext.RequestServices.GetService<UserManager<MyUser>>();\n\n        var loggerFactory = context.HttpContext.RequestServices.GetService<ILoggerFactory>();\n        Logger = loggerFactory.CreateLogger(GetType());\n        // Check if Action is annotated with [AllowAnonymous]\n        var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;\n        var anonymousAllowed = controllerActionDescriptor.MethodInfo\n            .GetCustomAttributes(inherit: true)\n            .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));\n\n        if (!anonymousAllowed)\n        {\n            ApplicationUser = UserManager.GetUserAsync(User).Result;\n            if (ApplicationUser == null)\n                // do some stuff\n            Logger.LogInformation("User is {UserId}", CurrentUser.Id);\n        }\n        else\n        {\n            Logger.LogInformation("User is {User}", anonymous);\n        }\n    }\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

奖励:从这个基础派生的每个控制器都已经有一个 UserManager、ILogger 和 CurrentUser 的实例。

\n\n

希望这接近您\xc2\xb4 正在寻找的东西......

\n