1
votes

I have an ASP.net MVC web application that uses Microsoft's Owin middleware (Microsoft.Owin.Security.OpenIdConnect) to configure OpenID Connect authentication. My identity provider (Okta) is configured to support refresh tokens and I have confirmed that it is working. When signing in, my application receives an Access, ID and Refresh Token as expected. These tokens are validated and returned to the client in a cookie called ".AspNet.Cookies" (the default). On each request, the cookie and these tokens are parsed into a set of claims. Great so far. ????

The Owin (Katana) middleware does not appear to do anything further with the Refresh Token, so I have implemented a token client to request a new Access Token from my IdP using the Refresh Token. This is working as expected. ????

Two questions:

  1. When and where should the application check to see if the Access Token is expired and request a new one?
  2. After receiving new a access, id, and refresh token, how and where should the application update the user identity, claims and cookie?
1

1 Answers

2
votes

OWIN COOKIE UPDATES

I believe the comment at the end of this post has the type of code you can write - I remember using similar code a few years back.

With OWIN you are using a server side stack secured by cookies so I'm not sure where access tokens are actually used, but maybe one of these is true?

  • The C# back end uses tokens to call an API
  • The Web UI downloads tokens from the web back end and makes Ajax calls to an API

PATTERN FOR HANDLING EXPIRED TOKENS

The only reliable pattern to handle expiry is to do this in the API client code:

  • When you get a 401 response from the API
  • Try to refresh the token and retry the API call with a new access token
  • If you can't refresh the token, redirect the user to sign in again

I always implement this with 2 classes, as in this SPA code of mine:

If the Web UI is getting tokens from the web back end and then calling an API, your web back end could provide MVC operations similar to those in my authenticator class:

  • getAccessToken - get the current access token, though it may fail with a 401
  • refreshAccessToken - use this if a 401 is received and you need a new token

TOKEN EXPIRY TIMES

It is also possible to check token expiry times in the background - to reduce the number of client 401s. This is not a full solution however, since 401s can occur for other reasons in addition to expiry.