Moiz
Moiz

Reputation: 2439

Owin Token expires even after continuous activity with server

Hello I am creating an application, where I am using Owin Tokens to validate the user authority and authorization.

I am able to generate the token along and it is setting the expiry as expected.

Issue

What if I have set the expiry for this token to 30 minutes, and the user was inactive till 25 minutes and on 26th minutes he started using the application, and in middle of work, on 30th minute the token will expire and all data could be lost.

How can I keep the token valid, like we had forms authentication that it will just expire after inactivity of 30 minutes. ?

public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
    //Rest of code is here;
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new SimpleAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }

Upvotes: 2

Views: 3279

Answers (1)

Artiom
Artiom

Reputation: 7847

What I've done in my application:

When application starts it checks

  1. if "expire date - 30s" < now than refresh token and update expire date. Execute step 2
  2. Reschedule refreshTokenIfNeededfunction in "expire date - 30s - now" seconds

sample:

public refreshTokenIfNeeded(): void {

   var self = this;

   var tokenHolder = self.tokenService.getToken();
   if (tokenHolder == null || !tokenHolder.refreshToken) {
      self.logout();
      return;
   }

   var expireTimeInMiliseconds = (new Date(tokenHolder.expirationTime).getTime() - 30000 - new Date().getTime());
   if (expireTimeInMiliseconds > 0) {
      setTimeout(() => self.refreshTokenIfNeeded(), expireTimeInMiliseconds);
      return;
   }

   var data = "grant_type=refresh_token&refresh_token=" + tokenHolder.refreshToken + "&client_id=" + self.externalAuthService.getClientId();

   self.$http.post('/token', data, {
         headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
         }
      })
      .success((response: ILoginTokenResponse) => {
         self.persist(response);

         setTimeout(() => self.refreshTokenIfNeeded(), (response.expires_in - 30) * 1000);

      }).error(() => {
         this.logout();
      });
}

Upvotes: 2

Related Questions