首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用OWIN Jwt承载身份验证记录身份验证结果

如何使用OWIN Jwt承载身份验证记录身份验证结果
EN

Stack Overflow用户
提问于 2018-01-31 09:24:20
回答 2查看 4.3K关注 0票数 6

我想记录对我的.netcore webapi的所有调用的统计信息。

为此,我已经添加了一个IAsyncActionFilter,它可以处理所有的操作。

但是,我还启用了Jwt Bearer身份验证,并且正在使用控制器上的AuthorizeAttribute来限制访问。当访问被拒绝时,将不会被击中。

为身份验证添加一些自定义日志记录(statsd),特别是失败的最佳方法是什么?

代码语言:javascript
复制
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 Events,但我不能让它工作。

编辑:看起来我在没有令牌的情况下访问api,JWT处理程序不调用Events.AuthenticationFailed就返回AuthenticateResult.NoResult()

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

编辑2:非常令人沮丧。看起来正确的日志位置将在Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter中,但这是在使用[Authorize]时自动添加的,并且不可能覆盖、删除或替换?

EN

回答 2

Stack Overflow用户

发布于 2018-01-31 19:47:59

JwtBearerOptions.cs类公开一个JwtBearerEvents参数,您可以在其中声明如下所示的事件

代码语言:javascript
复制
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;
            }
        };

    });
票数 5
EN

Stack Overflow用户

发布于 2018-01-31 16:43:04

我没有任何经验的Jwt比勒认证-但我们有类似的情况。我们最终得到了一个新的BaseController,在这里我们能够记录基本的用户信息并区分[AllowAnonymous][Authorize]

代码语言:javascript
复制
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的实例。

希望这接近你想要的.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48538601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档