c# - 如何使用 OWIN Jwt Bearer Authentication 记录认证结果

标签 c# .net-core asp.net-core-mvc jwt owin

我想记录对我的 .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();
...
}

我注意到 JwtBearerOptionsJwtBearerEvents 事件,但我无法让它工作。

编辑:看起来我在没有 token 的情况下访问 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] 时,它会自动添加并且无法覆盖,删除或替换?

最佳答案

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/

相关文章:

c# - 重定向到区域总是给出 404 或错误的重定向

azure-sql-database - 在 Entity Framework 7/MVC 6 上动态更改连接字符串(每个请求)

c# - MediatR 发布和 MediatR 发送

asp.net-mvc - ASP.NET MVC 6 中的基本 View 页面

c# - `Timer` 组件不够准确,有替代方案吗?

c# - 使用 LINQ to Entity Framework 进行复杂字符串匹配

c# - 类库和 .NET Core 类库模板有什么区别?

c# - 使用 netcoreapp3.0 安装 dotnet-ef 时遇到问题

c# - 如何限制 Parallel.ForEach?

c# - Azure函数不运行异步方法