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# - 将文件上传到 Azure 上托管的 ASP.NET Core Web 应用程序的目录

c# - Windows 任务栏右键菜单中的标题

entity-framework - 如何向 CaSTLe Windsor 注册 Ef core db 上下文?

c# - 在 linux 服务上处理 kill - .NET Core 1.1

.net - .net core mvc 中 session 超时时如何重定向

javascript - 配置 Gulp 以反射(reflect) css 更改

c# - IServiceCollection 不包含 AddQuartz 的定义

c# - 上传文件 ASP.NET 5

c#:如何读取文件的一部分? (DICOM)

c# - .NET 安装包有时无法完全删除以前的版本