Azure ACS with HTTPS and multiple instances Error - azure

I just followed the following instructions here.
And found a couple blog entries here and here to be rather helpful.
But I am still getting weird issues with my ASP.NET MVC3 app running on Azure on an HTTPS end point. I have the HTTPS certificate loaded and it has deployed consistently on a single role instance for quite some time without any issue. However, just recently I started deploying multiple instances and ran into the 'Key not valid for use in specified state' and the 'Value cannot be null. Parameter name: certificate' erors.
But I have a new one now:
'Unable to read beyond the end of the stream.'
Looks pretty vanilla. It doesn't become obvious that its an issue with the move from DPAPI to the RSA cookie transform until you look at the stack trace.
[EndOfStreamException: Unable to read beyond the end of the stream.]
System.IO.MemoryStream.InternalReadInt32() +12750266
Microsoft.IdentityModel.Web.RsaEncryptionCookieTransform.Decode(Byte[] encoded) +369
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +189
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +862
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +109
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +356
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +123
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +61
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
I have added the following code to global.asax:
void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
//
// Use the <serviceCertificate> to protect the cookies that are sent to the client.
//
List<CookieTransform> sessionTransforms = new List<CookieTransform>(
new CookieTransform[] {
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate) });
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
As well as this code:
void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
// In the Windows Azure environment, build a wreply parameter for the SignIn request
// that reflects the real address of the application.
HttpRequest request = HttpContext.Current.Request;
Uri requestUrl = request.Url;
StringBuilder wreply = new StringBuilder();
wreply.Append(requestUrl.Scheme); // e.g. "http" or "https"
wreply.Append("://");
wreply.Append(request.Headers["Host"] ?? requestUrl.Authority);
wreply.Append(request.ApplicationPath);
if (!request.ApplicationPath.EndsWith("/")) wreply.Append("/"); e.SignInRequestMessage.Reply = wreply.ToString();
}

I recently worked on similar problem and the potential reason was combination of older SDK and ACS. If you try using SDK 1.6 and ACSv2 setting, i hope this problem will not occur and if you still see the problem, I would be glad to work with you to root cause it.

Related

RBAC issues using MassTransit with Azure service bus and MSI authentication

We are using MassTransit (v.5.5.5) with Azure Service Bus in a .net core v.2.2 application running in a container within Kubernetes. During the Bus setup we create a token using the managed service identity (MSI), like this...
var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
IServiceBusHost busHost = cfg.Host(new Uri(Settings.Host), h =>
{
h.OperationTimeout = TimeSpan.FromSeconds(5);
h.TokenProvider = tokenProvider;
h.TransportType = Settings.TransportType;
});
...
}
Within Azure, the MSI is configured with all 3 Service Bus permissions (Owner, Sender and Receiver) - as decribed here.
When the application starts authentication seems to happen successfully but when MassTransit begins to listen on the specific queues we create it fails with the following error:
MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport Error: 0 :
ReceiveTransport Faulted: sb://hostname.servicebus.windows.net/some-custom-queue,
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check,
please make sure service resource provider is registered on your tenant.
Points to note:
The application does create the temporary bus queue, and there are no errors to do with accessing it.
The application does not create our custom queues.
If the MSI permissions are removed then no queues are created and the error is different: Authorization failed for specified action: Manage,EntityWrite.
For what it's worth we are using the AmqpWebSockets transport type.
It seems weird that the temporary queue is created but not our application-specific ones.
So I guess my question is this... have I done anything wrong or is this something that is not yet available for MassTransit using Service Bus with MSI?
Thanks in advance.
We came across the same issue. We are using Mass Transit 6.* and Azure Service Bus. When switched to MSI we start see the same error:
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check, please make sure service resource provider is registered on your tenant. TrackingId:2644d62a-83a9-444f-8aeb-b4bdee2fa84d_G30, SystemTracker:NoSystemTracker, Timestamp:2020-02-13T15:54:49
at Microsoft.Azure.ServiceBus.Management.ManagementClient.SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.ServiceBus.Management.ManagementClient.PutEntity(String path, String requestBody, Boolean isUpdate, String forwardTo, String fwdDeadLetterTo, CancellationToken cancellationToken)
at Microsoft.Azure.ServiceBus.Management.ManagementClient.CreateTopicAsync(TopicDescription topicDescription, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.<>c__DisplayClass25_0`1.<<RunOperation>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.RunOperation[T](Func`1 operation)
at MassTransit.Azure.ServiceBus.Core.Contexts.ServiceBusNamespaceContext.CreateTopic(TopicDescription topicDescription)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.ConfigureTopology(NamespaceContext context)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.<>c__DisplayClass5_0.<<Send>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at GreenPipes.PipeExtensions.OneTimeSetup[T](PipeContext context, Func`2 setupMethod, PayloadFactory`1 payloadFactory)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.Send(NamespaceContext context, IPipe`1 next)
at GreenPipes.Agents.AsyncPipeContextPipe`1.Send(TContext context)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at MassTransit.Azure.ServiceBus.Core.Pipeline.ClientContextFactory.CreateSharedContext(Task`1 context, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport.<Receiver>b__12_0()
at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
Finally we found that ASB Sdk Microsoft.Azure.ServiceBus.Management.ManagementClient doesn't allow to create topics with slashes in path when tokens from MSI used. This code below return the same error:
try
{
var address = "sb://[name].servicebus.windows.net";
var tokenProvider = new TokenProvider.CreateManagedIdentityTokenProvider();();
var _managementClient = new ManagementClient(address.ToString(), tokenProvider);
var topicDefinition = new TopicDescription("myNewTopic/22222");
await _managementClient.CreateTopicAsync(topicDefinition);
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
Since MT uses special naming convention to setup messaging topology, we get topic path with namespace of particular message type. If we have message MassTransitTest.Message1 it will be converted to topic MassTransitTest/Message1 (with slash). To fix this we setup our own IEntityNameFormatter
public class MyEntityNameFormatter : IEntityNameFormatter
{
readonly IMessageNameFormatter _formatter;
public MyEntityNameFormatter()
{
_formatter = new ServiceBusMessageNameFormatter();
}
public string FormatEntityName<T>()
{
var entityName = _formatter.GetMessageName(typeof(T)).ToString().Replace("/",".");
return entityName;
}
}
and then
var bus = Bus.Factory.CreateUsingAzureServiceBus(configurator =>
{
...
configurator.MessageTopology.SetEntityNameFormatter(new MyEntityNameFormatter());
...
This fixed our issue. (We tried use ~ instead of . but got some validation errors, so decided use dots)
I have been able to reproduce the same error using Azure Service Bus SDK code directly in a .NET Core (3.0) ASP.NET application hosted in an AppService with Managed Identity.
string serviceBusNamespace = "busnamespace_here";
string queueName = "with_service_name/test"; // NOT working with RBAC
// string queueName = "testrbac"; // Works with RBAC - no /
var msiTokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
var qc = new QueueClient(new Uri($"sb://{serviceBusNamespace}.servicebus.windows.net/").ToString(), queueName, msiTokenProvider);
var message = new Message(Encoding.UTF8.GetBytes($"Test {DateTime.Now.ToShortTimeString()}"))
{
ContentType = "application/text",
Label = "Scientist",
MessageId = Guid.NewGuid().ToString()
};
try
{
await qc.SendAsync(message);
}
catch (Exception ex)
{
return View(ex.ToString());
}
I found out that the error seems to be caused by the presence of a / in the queue name. It's a character that is allowed in the Service Bus but it doesn't seems to works quite nicely with RBAC Service Bus feature.
The same code works well if you use a SAS Policy instead of Managed Identity/Client Secret.
Here is my test Service Bus in image (using Service Bus Explorer) :
Mass Transit
I know Mass Transit can use entity path with slash character in it. Does that means we can't use RBAC to access those entities ?
I wasn't able to find what is the root cause.

OkHttp CookieJar saveFromResponse method

I created a simple project which using CookieJar. Now I am trying to understand when saveFromResponse method works. But I see in my logs that loadForRequest works fine, but I doesn't see saveFromResponse logs. Why? At what time of process this method works? Can we use only intercept method if we works with cookies or may be we have a special situation for using CookieJar?
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new ReceivedCookiesInterceptor())
.cookieJar(new CookieJar() {
private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();
#Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
Log.d(TAG,"saveFromResponse");
cookieStore.put(url, cookies);
}
#Override
public List<Cookie> loadForRequest(HttpUrl url) {
Log.d(TAG,"loadForRequest");
List<Cookie> cookies = cookieStore.get(url);
return cookies != null ? cookies : new ArrayList<Cookie>();
}
})
.build();
Request request = new Request.Builder()
.url("http://www.publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
response.body().close();
I know it's a bit late, but I was struggling with the exact same issue and then I realised that saveFromResponse is only called on new cookies. This means that all the cookies you set on loadForRequest are not received in saveFromResponse.
That's the behaviour I could infer, but I'm not sure if it is the one that it should be, as this way you can't get cookie value updates from remote server.
Did you experienced the behaviour that only on the first request after OkHttpClient creation the cookies are received and not on the rest of the requests?
Please, someone with more knowledge that can shed some light?

Connect to a SharePoint site when IIS requires client certificates

I currently have an application developed in C# that helps me in managing permissions on our Share-point 2013 site. Recently, I learned we may be loosing our local instance and moving to another instance that's behind a cac enforced IIS. I have converted one of my test sites to require certificates and have tried several way to send the cert to the IIS server but I still get
"The remote server returned and error: (403) Forbidden.
Below is a few things I have tried.
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.ClientCertificates.Add(pki.GetClientCertificate());
handler.UseProxy = false;
using (var client = new HttpClient(handler))
{
context connection code here
}
the pki.GetClientCertificate is a method, I made that returns a selected certificate in this case my cac cert. Its funny that SharePoint designer connects without issue or prompt. Any help on this matter would be much appreciated.
Just to add some more things I have tried
context.Credentials = new SharePointOnlineCredentials(uli.username, uli.password);
the uli username is the certificate converted to username I have a class that dose the conversion. the password is the pin converted to a secure string. I get the same message even when adding the credentials to the context.
I found a workable but slow solution here:
http://sharepoint.findincity.net/view/635399286724222582121618/ssl-certificate-error-when-using-client-object-model
The only issue with this is every time I call the context I have to send the certificate chain. One thing I changed from this users code is the following.
static void context_ExecutingWebRequest(object sender, WebRequestEventArgs e)
{
IntPtr ptr = IntPtr.Zero;
X509Certificate2 certificate = null;
X509Certificate t = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
// Nothing to do if no cert found.
HttpWebRequest webReq = e.WebRequestExecutor.WebRequest;
//webReq.Proxy = new WebProxy("http://[ProxyAddress]");
//Specify a proxy address if you need to
// X509Certificate cert = pki.GetClientCertificate();
foreach (X509Certificate c in store.Certificates)
{
webReq.ClientCertificates.Add(c);
}
}
I just dumped all my certificates into the request because I didn't want to have a prompt every time I clicked something. So if anyone has a more efficient way to do this let me know.
The code below shows the use of the clientcontext and how it validates your cert
using (context = new ClientContext(siteurl))
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
return validationResult;
};
context.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(context_ExecutingWebRequest);
//add all your context commands below this line
}

Custom maintenance mode module does not work on Azure Web Role

I've created and registered custom http module to show maintenance message to user after administrator turns on maintenance mode via configuration change.
When I pass request for html it should return custom html loaded from file, but it returns message: "The service is unavailable." I can't find that string in my entire solution. Custom log message from custom maintenance module is written to log4net logs.
... INFO DdiPlusWeb.Common.MaintenanceResponder - Maintenance mode is on. Request rejected. RequestUrl=...
Seems something is miss configured in IIS on Azure. Something intercepts my 503 response. How to fix it?
Module code
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
if (AppConfig.Azure.IsMaintenance)
{
MaintenanceResponder responder = new MaintenanceResponder(context, MaintenaceHtmlFileName);
responder.Respond();
}
}
Interesting part of responder code.
private void SetMaintenanceResponse(string message = null)
{
_context.Response.Clear();
_context.Response.StatusCode = 503;
_context.Response.StatusDescription = "Maintenance";
if (string.IsNullOrEmpty(message))
{
_context.Response.Write("503, Site is under maintenance. Please try again a bit later.");
}
else
{
_context.Response.Write(message);
}
_context.Response.Flush();
_context.Response.End();
}
EDIT: I lied. Sorry. Maintenance module returns the same message for requests that expect json or html.
This answer led me to the solution.
I've added another line to SetMaintenanceResponse method.
_context.Response.TrySkipIisCustomErrors = true;
It works now. Here is more about what it exactly means.

The data protection operation was unsuccessful on Azure using OWIN / Katana

I'm trying to implement password reset on an OWIN/Katana based ASP.NET MVC website running in Azure.
It works fine when run locally but fails in production.
I create a UserToken Provider
userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("PasswordReset"))
But when I attempt to generate the token as follows
var resetToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
I get following exception.
System.Security.Cryptography.CryptographicException: The data
protection operation was unsuccessful. This may have been caused by
not having the user profile loaded for the current thread's user
context, which may be the case when the thread is impersonating.
at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope)
at System.Security.Cryptography.DpapiDataProtector.ProviderProtect(Byte[]
userData)
at System.Security.Cryptography.DataProtector.Protect(Byte[] userData)
at Microsoft.Owin.Security.DataProtection.DpapiDataProtector.Protect(Byte[]
userData)
at Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider 2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
at Microsoft.AspNet.Identity.UserManager`2.d__e9.MoveNext()
If the host server is a virtual machine it could be exactly what the error message says. Check if your Application Pool in IIS really has Load User Profile set to true like the exception says:
In the Connections pane, expand the server name, and then click Application Pools.
Right click on you Pool
Advanced Settings
I have the same problem when I try to generate token with ASP .Net identity and custom login function in Web API.
"The data protection operation was unsuccessful. This may have been
caused by not having the user profile loaded for the current thread's
user context, which may be the case when the thread is impersonating."
What I did is just simply create an Application Setting called WEBSITE_LOAD_USER_PROFILE in Microsoft Azure and set it to 1. That solution works for me.
You can see the detail here
Please see my my answer to this question. A much simpler solution can be achieved by utilizing IAppBuilder.GetDataProtectionProvider()
I found a solution. I'm not exactly sure if all steps are necessary to it work, but now my app works perfectly:
1.- Update your web.config to support securityTokenHandlers
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
in the configSections node. And
<securityTokenHandlers>
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
System.IdentityModel, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=B77A5C561934E089" />
<add
type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,
System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=B77A5C561934E089">
<sessionTokenRequirement lifetime="00:30:00"></sessionTokenRequirement>
</add>
</securityTokenHandlers>
</identityConfiguration>
as a regular node.
2.- In your Startup.Auth.cs file, update your ConfigureAuth(IAppBuilder app) like this:
public void ConfigureAuth(IAppBuilder app)
{
UserManagerFactory = () =>
{
var userManager = new UserManager<SIAgroUser>(new UserStore<UserType>(new SIAgroUserDbContext()));
IDataProtectionProvider provider = app.GetDataProtectionProvider();
//userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<UserType>(provider.Create("PasswordReset") );
if (provider != null)
{
userManager.UserTokenProvider = new DataProtectorTokenProvider<UsertType, string>(provider.Create("PasswordReset"));
}
return userManager;
};
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
}
3.- Clean up the constructor of your Startup class like this:
static Startup()
{
PublicClientId = "self";
}
That worked for me :) I hope it works for you too
This error happens for me on a shared hosting provider, at the line:
var provider = new DpapiDataProtectionProvider("SITENAME");
The solution was quite simple. First change the above line to this:
var provider = new MachineKeyProtectionProvider();
Then create a new file, which I have in my Utilities namespace, like so:
using Microsoft.Owin.Security.DataProtection;
using System.Web.Security;
namespace <yournamespace>.Utilities
{
public class MachineKeyProtectionProvider : IDataProtectionProvider
{
public IDataProtector Create(params string[] purposes)
{
return new MachineKeyDataProtector(purposes);
}
}
public class MachineKeyDataProtector : IDataProtector
{
private readonly string[] _purposes;
public MachineKeyDataProtector(string[] purposes)
{
_purposes = purposes;
}
public byte[] Protect(byte[] userData)
{
return MachineKey.Protect(userData, _purposes);
}
public byte[] Unprotect(byte[] protectedData)
{
return MachineKey.Unprotect(protectedData, _purposes);
}
}
}
Et voila! Problem solved. Just remember, in your password reset controller method, you will also have to use this provider, otherwise you will get an Invalid Token error.
I put this one on ice for a while but was forced to come back to it. I found the solution here:
Generating reset password token does not work in Azure Website
Getting the UserManager from the Owin Pipeline, as its set in App_Start/Startup.Auth.cs, works on Azure.
I'm unsure as to how this works specifically.
The DpApi should work in Azure with the solution described in the first link.
If the DpApi has a static machine key set in Web.config all server machines will be able to decrypt the encrypted data created by another machine in your webfarm is the understanding behind this.
(code as given in the standard template - from AccountController.cs)
private UserManager userManager;
public UserManager UserManager
{
get { return userManager ?? HttpContext.GetOwinContext().GetUserManager<UserManager>(); }
private set { userManager = value; }
}
After me and two other people have messing with this error for dayS we discovered something intresting in the IIS. If the Load User Profile is switched following is created in applicationhost.config
loadUserProfile="true"
but when you turn it off it also works, but now the line
loadUserProfile="false"
has been added. So difference was that default value had to be written in applicationhost.config to make it work. Some cache is recreated?

Resources