I have hosted an Owin WebAPI Server in an Azure Worker Role.
The Owin Authentication middleware seems to use the MachineKey to encrypt and generate Tokens.
This works perfectly when I have only one instance of this role, but as soon as I want to use several instances, the tokens generated by each instance are differents.
This is the same problem as a web farm, Azure automatically solves this for WebRoles using the same .net Machine Key for all instances in Web.config.
But this does not work for Worker Role instances.
Is there a trick to have Azure using the same machine key for all the intsances of a worker Role ?
Seems it would be easier than rewriting code to generate the tokens for Owin.
If your self-hosted application can reference System.Web
, then you can use the same MachineKey implementaiton that the Microsoft.Owin.Host.SystemWeb
does.
Put the configuration/system.web/machineKey
settings in your App.config just like it is in the Web.config.
Reference reference System.Web
and add the following class:
public class MachineKeyDataProtector : IDataProtector
{
private readonly string[] purposes;
public MachineKeyDataProtector(params string[] purposes)
{
this.purposes = purposes;
}
public byte[] Protect(byte[] userData)
{
return MachineKey.Protect(userData, this.purposes);
}
public byte[] Unprotect(byte[] protectedData)
{
return MachineKey.Unprotect(protectedData, this.purposes);
}
}
Then set your authentication options using that class:
var authenticationOptions = new OAuthBearerAuthenticationOptions
{
AccessTokenFormat = new TicketDataFormat(new MachineKeyDataProtector(
typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1")),
AccessTokenProvider = new AuthenticationTokenProvider(),
};