How to log authentication failure reasons when using OWIN and JWT?

狂风中的少年 提交于 2020-06-25 10:31:12

问题


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

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.


回答1:


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

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.

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

And use it like this:

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


来源:https://stackoverflow.com/questions/33578498/how-to-log-authentication-failure-reasons-when-using-owin-and-jwt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!