使用OWIN和JWT时如何记录身份验证失败原因? [英] How to log authentication failure reasons when using OWIN and JWT?

查看:156
本文介绍了使用OWIN和JWT时如何记录身份验证失败原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用c#自托管OWIN服务器,并已将我的应用程序配置为使用JWT进行授权,如下所示.这可以正常工作,并且使用401 Unauthorized拒绝无效的令牌,并接受有效的令牌.

I am using a c# self hosted OWIN server and have configured my application to use authorise with JWT as below. This works properly, and invalid tokens are rejected with a 401 Unauthorized and valid tokens are accepted.

我的问题是我怎么写为什么请求被拒绝的日志.它过期了吗?这是错误的听众吗?没有令牌吗?我希望所有失败的请求都被记录下来,但似乎找不到任何示例.

My question is how can I write a log of why requests are rejected. Was it expired? Was it the wrong audience? Was no token present? I want all failed requests to be logged, but I can't seem to find any example of how.

public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {

            // Configure Web API for self-host. 
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // Enable 
            config.Filters.Add(new AuthorizeAttribute());

            appBuilder.UseJwtBearerAuthentication(new JwtOptions());
            appBuilder.UseWebApi(config);
        }
    }

JwtOptions.cs

JwtOptions.cs

public class JwtOptions : JwtBearerAuthenticationOptions
    {
        public JwtOptions()
        {
            var issuer = WebConfigurationManager.AppSettings["CertificateIssuer"];
            var audience = WebConfigurationManager.AppSettings["CertificateAudience"];

            var x590Certificate = Ap21X509Certificate.Get(WebConfigurationManager.AppSettings["CertificateThumbprint"]);

            AllowedAudiences = new[] { audience };
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2(x590Certificate.RawData))
            };
        }
    }

我猜想我需要实现自己的验证才能做到这一点,但不确定如何实现.

I am guessing I will need to implement my own validation to do this, but not sure how to implement that either.

推荐答案

我知道已经很晚了,但是对于如何努力寻找答案可能很有用.

I know that it is quite late, but can be useful for one how is struggling to find an answer.

基本上,AuthenticationMiddleware具有嵌入式日志记录.您只需要将OWIN日志重定向到您正在使用的记录器. NLog.Owin.Logging 对我来说效果很好. log4net也有类似的解决方案.

Basically AuthenticationMiddleware has embedded logging. You just need to redirect OWIN logs to logger you are using. NLog.Owin.Logging works well for me. There is similar solution for log4net.

有替代解决方案.扩展JwtSecurityTokenHandler并手动记录原因.

There is alternative solution. Extend JwtSecurityTokenHandler and log the reason manually.

public class LoggingJwtSecurityTokenHandler : JwtSecurityTokenHandler
{
    public override ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        try
        {
            return base.ValidateToken(securityToken, validationParameters, out validatedToken);
        }
        catch (Exception ex)
        {
            //log the error
            throw;
        }
    }
}

并像这样使用它:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    TokenHandler = new LoggingJwtSecurityTokenHandler()
});

这篇关于使用OWIN和JWT时如何记录身份验证失败原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆