OAuth2 WebApi Token Expiration OAuth2 WebApi Token Expiration asp.net asp.net

OAuth2 WebApi Token Expiration


We have a similar situation, with different clients that have different token timeouts so we wanted to be able to set the expiration accordingly. In the AuthenticationTokenProvider we implemented we were setting the expiration but it was being overwritten by the time the token was being signed.

The solution we ended up happy with was overriding the TokenEndpoint method. We're then able to implement a client specific expiration :

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)    {        if (context.TokenIssued)        {            // client information            var accessExpiration = DateTimeOffset.Now.AddSeconds(accessTokenTimeoutSeconds);            context.Properties.ExpiresUtc = accessExpiration;        }        return Task.FromResult<object>(null);    }

*Edited to resolve a race condition.


The behavior you're seeing is directly caused by the fact the OAuth2 authorization server always discards your own expiration when you set it in the GrantResourceOwnerCredentials notification (the other Grant* notifications are also impacted): https://github.com/jchannon/katanaproject/blob/master/src/Microsoft.Owin.Security.OAuth/OAuthAuthorizationServerHandler.cs#L386

A work around is to set the expiration date in AuthenticationTokenProvider.CreateAsync (the class you use for OAuthAuthorizationServerOptions.AccessTokenProvider):

Simply set context.Ticket.Properties.ExpiresUtc with the expiration date of your choice, and it should work as intented:

public class AccessTokenProvider : AuthenticationTokenProvider{    public override void Create(AuthenticationTokenCreateContext context)    {        context.Ticket.Properties.ExpiresUtc = // set the appropriate expiration date.        context.SetToken(context.SerializeTicket());    }}

You can also take a look at AspNet.Security.OpenIdConnect.Server, a fork of the OAuth2 authorization server offered by OWIN/Katana that natively supports setting the expiration date from GrantResourceOwnerCredentials: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev


I'll throw this out here, as of right now, there is simpler way without creating a new class, it's just setting options:

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions(){    ...    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),    ..};