Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web api bearer token timeout some minutes later

I am using asp.net web api and token based authentication. My token options is set success token expire time to 14 days later.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new SimpleAuthorizationServerProvider(),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

And my generated token is like this.

{
  "access_token": "Mg5oQAzt9RLSUezxPYNQ7JRcJqo-uPxfOgOGHKkrJ_q56g0H8x-sjKm1mkjND0VAK3H22nwFlGNk5wfTocCb5mKMvTYwsZAv5sh0SACHdbb_9BGftMuqbFdm6wH0wXF-Sq3noF7hc2FeUUauhDfrBq5jTSou4NO3EBwjc0jj3v-yQzPGMCFxq2Q8C9uhat14rGYteYqj5mX3L5JtwHrobePL2R9lcnagNIMa44GUWQ8DVR2urP4KCrDHJf1G5pIfv94uB85I7sbf0nse7VvhYp058I8voNR9_zD1XC5-AODQJ16F484zxQokX1BWJ3gfgd86zJr2O9iKsA",
  "token_type": "bearer",
  "expires_in": 1209599,
  ".issued": "Sat, 20 Feb 2016 13:15:10 GMT",
  ".expires": "Sat, 05 Mar 2016 13:15:10 GMT"
}

I am saving this info in a cookie and use in my application. But some minutes later my access token validation is expiring and 401 http error.

I am trying to GET request from Fiddler and postman but gives 401 authorization error.

like image 387
barteloma Avatar asked Dec 24 '22 09:12

barteloma


1 Answers

From this post: ASP.NET Web API Authorization tokens expiring early

Looks like the machine key used to encrypt and decrypt tokens is re-generated every time the application pool is recycled causing our application unable to decrypt the previously encrypted tokens. Try setting a fixed machine key as suggested in the post.

Side note:

From application design perspective, we should not set a big timespan for access tokens, access tokens should be short-lived and used together with refresh tokens: Why Does OAuth v2 Have Both Access and Refresh Tokens?

In order to generate refresh tokens in owin, provide the RefreshTokenProvider to your OAuthAuthorizationServerOptions:

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new SimpleAuthorizationServerProvider(),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true,

    RefreshTokenProvider = //your refresh token provider.
};
like image 65
Khanh TO Avatar answered Jan 14 '23 01:01

Khanh TO