Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

jwt

owin

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.

like image 730
jmc Avatar asked Nov 07 '15 02:11

jmc


People also ask

How use JWT token for authentication and authorization?

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.

What is difference between JWT and oauth2?

JWT token vs oauth token: JWT defines a token format while OAuth deals in defining authorization protocols. JWT is simple and easy to learn from the initial stage while OAuth is complex. OAuth uses both client-side and server-side storage while JWT must use only client-side storage. JWT has limited scope and use cases.


1 Answers

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()
});
like image 167
Evgeni Lipatov Avatar answered Oct 10 '22 05:10

Evgeni Lipatov