We have ASP.NET MVC 5.x WebAPI 2.x web-application running as Azure cloud service and use token authorization for REST API calls to our service.
The problem is: each time we redeploy our app - all current tokens become invalid (server returns "non-authorized" response for any request).
The question is: why does it happen and how to prevent such behavior?
UPD: Here is the code that issue token:
public string GetOAuthToken(IUser user) {
if (user != null) {
var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = DateTime.UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(36600)); //About 100 years
string AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
}
return "";
}
UPD2: It seems the token generated by default token endpoing (/Token) does not become invalid after redeploy - so the problem (I think) is in some properties which we set for our "handmade" token. Where can I find the code which creates the default token (returned by /Token endpoint)?
Yes, it is possible to reuse the authentication token for multiple requests. We can achieve it by creating a collection and adding all the requests having the same authentication token to that collection and then assigning the auth token to the same collection.
It is best practice to encrypt these tokens in the database. If your database is compromised, an attacker could use the tokens to access any information or actions provided by the 3rd-party services.
To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.
Problem solved. It appears that AccessTokenFormat created by default uses machineKey to generate tokens. Obviously those keys were different for production and staging VMs. The solution is rather easy. You need to generate your own machine key and add it into Web.Config file of your project:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" relaxedUrlToFileSystemMapping="true" />
<machineKey
validationKey="YOUR VALIDATION KEY GOES HERE"
decryptionKey="YOUR DECRYPTION KEY GOES HERE"
validation="SHA1" decryption="AES"
/>
For more information about this approach you can read "Step 5..." section of this article: http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With