How to call same request again after regenerating token on unauthorized requests

Visitor

Hi,

I am working on .Net Core MVC 3.1 application and I want request should be retried if it failed due to token expired. 
So, I have just .Net core mvc application without API project.


Just like in any API project we have option to refresh token if it is expired and try same request again I want the same thing for .net core mvc application.

To let user login I can generate cookie but that lacks refreshing cookie at regular interval as we can do with access token using refresh token, so I have chosen to authenticate using Bearer scheme in.Net core MVC application (If it can be done using cookie itself then I am fine with that as well, please let me know if that is possible and how)


So, in current situation, I can write middleware to check status code of response but I am not getting that how I can make same request with same request payload after refreshing token in the middleware. 

Ideally, I would like to register middlewares like below

app.UseCustomMiddleware();
app.UseAuthentication();
app.UseAuthorization();

My authentication service is registered like below to let app know about token expiration.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
 options.Events = new JwtBearerEvents
 {
  OnAuthenticationFailed = context =>
  {
   if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
   {
     context.Response.Headers.Add("Token-Expired", "yes");
   }
   return Task.CompletedTask;
  }
 }
}

Once UseCustomMiddleware knows request failed due to token expired (which I can check reading response headers to check if it has Token-Expired header with value yes) then I can regenerate it but don't know how to resend same request after refreshing token.

Please let me how it can be done or there is better way of doing the thing.
Thanks!

0 Replies