owin: Catch SecurityTokenExpiredException exception

849 views Asked by At

I have an asp.net web api project that uses OpenID for authentification. I need to find a way to log the unauthorized requests. I've tried this, but it's not working:

public class LogMiddleware : OwinMiddleware
{

    public AuditMiddleware(OwinMiddleware next) : base(next) {}

    public override async Task Invoke(IOwinContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        try
        {
            await this.Next.Invoke(context);
        }
        catch (Exception exception)
        {
            var body = ReadRequestBody(context);
            var request = JsonConvert.SerializeObject(new { context.Request.Headers, Body = body, QueryString = context.Request.QueryString.Value });
            this.factory.Create().Error().Exception(exception).AdditionalInfo("request", request).Write();
            throw;
        }
    }

..........

In visual studio, I am seeing:

Exception: Exception thrown: 'System.IdentityModel.Tokens.SecurityTokenExpiredException' in System.IdentityModel.Tokens.Jwt.dll ("IDX10223: Lifetime validation failed. The token is expired.

Exception: Exception caught: 'System.IdentityModel.Tokens.SecurityTokenExpiredException' in System.IdentityModel.Tokens.Jwt.dll ("IDX10223: Lifetime validation failed. The token is expired.

So is there a way to catch this exception and log it or the developers that wrote the libraries just wanted to hide the exceptions for no reasons?

0

There are 0 answers