Reputation: 1962
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)?
Upvotes: 5
Views: 1546
Reputation: 1962
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/
Upvotes: 4
Reputation: 1962
Not a complete answer but now we know the reason of this behavior at least.
The problem is in staging / production deployments of our cloud service. We deploy our service into a staging and then swap. In that moment the token, issued on previous deployment become invalid. If we do it second time (deploy to staging the same release and then swap) - it become valid again. So, obviously any issued token includes some linking with system (real or virtual) on which the service is running at the moment.
The main question that remains: Is it possible to remove that linking or to control it somehow?
Upvotes: 1