2

Instead of the usual response of Status : 400 and body message of "Error" : "invalid_client" when the token has expired, are there any methods of changing the status code and body to display something else?

Currently, I've managed to do something with headers as following :

 public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(context.Token, out ticket))
        {
            if (ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value.LocalDateTime < DateTime.Now)
            {
                context.Response.Headers.Add("Expired", new string[] { "Yes" });
            }

            context.SetTicket(ticket);

        }

    }

Any help anyone?

Thanks.

Jeremy Loh
  • 175
  • 1
  • 9

1 Answers1

2

You can implement a custom ASP.NET WebApi DelegatingHandler (if you want the validation to happen for all the requests) or ActionFilter (if you want the validation to happen for specific requests/per endpoint) to check whether the token is still valid and interrupt the request to return a more meaningful response. See the links for details.

I've implemented a simple one for your reference:

public class CustomTokenCheckMessageHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (HasMyTokenExpired())
        {
            return new HttpResponseMessage
            {
                StatusCode = System.Net.HttpStatusCode.Unauthorized,
                ReasonPhrase = "",
                Content = new StringContent("Test") // See HttpContent for more https://msdn.microsoft.com/en-us/library/system.net.http.httpcontent(v=vs.118).aspx
            };
        }

        return await base.SendAsync(request, cancellationToken);
    }

    public bool HasMyTokenExpired()
    {
        //Your custom logic here
        return true;
    }
}

Then you need to register it in the WebApiConfig file like this:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        /*
            All other config goes here
        */

        //This line registers the handler
        config.MessageHandlers.Add(new CustomTokenCheckMessageHandler());
    }
}
Martin
  • 475
  • 4
  • 14
  • Hi Martin, thanks for your response butt I can't seem to figure out how to apply that with the Owin and OAuth2.0 implementation. The MessageHandlers (from the Delegating Handler link) don't seem to apply as the webapi configuration happens after the app.UseOAuthAuthorization and same seems to be for the ActionFilter. – Jeremy Loh May 23 '18 at 13:48
  • See my answer again. I have added a simple one for your reference. – Martin May 24 '18 at 01:14
  • Hi Martin, I'm using Katana and do not use the webApiConfig class. Rather I have a startup class and by the time I have a HttpConfiguration it is way after the OAuth MiddleWare. – Jeremy Loh May 24 '18 at 09:40
  • It doesn't really matter. You should be able to register the delegating handler regardless and include your own logic there since you have access to the request context, headers, etc. – Martin May 24 '18 at 09:44