There are cases in Websites when we need to refresh a website user's authentication token, regardless of they are active or inactive. If a user is inactive, its easier to find the time and redirect user to a login page for re-authentication.
Let's see how we can force refresh a user auth token.
Parameters needed for the token refreshed:
var Data ="refresh_token="+Token+"&grant_type=refresh_token"
We will send the above parameters in the token method. Here, our token method will return a new access token and refresh_token.
API changes for the refreshed token
We have to append the refreshtokenprovider like below method in the startup class.
- static startup() {
- OAuth = new OAuthAutherizationserverOptions {
- TokenEndPointPath = new PathString("/Token"),
- Provider = new OAuthProvider(),
- AccessTokenExpireTimeSpan = Timespan.FromMInutes(20),
- AllowInsecureHttp = True,
- RefreshTokenProvider = new AppRefreshTokenProvider()
- }
- }
Code for AppRefreshTokenProvider
The AuthenticationTokenProvider class helps to extend the expiration time of the token. We need to override the Create and Recieve methods of AuthenticationTokenProvider class.
- Public class AppRefreshTokenProvider: AuthenticationTokenProvider {
- Public override void create(AuthenticationTokenCreateContext _context) {
- _context.Ticket.Properties.Expires = new DateTimeOffSet(DateTime.Now.AddMinutes(5));
- _context.SetToken(_context.SerializeTicket())
- }
- Public override void receive(AuthenticationTokenReceiveContext _context) {
- _context.DeserializeTicket(_context.Token);
- }
- }
The above method extends 5 minutes in the expiration time of the token.
In this blog, I have explained how you can refresh a token.