Exception AADSTS50011 is thrown when using azure ad authentication - authentication

I have been developing a C# MVC application. Using azure ad to authenticate the users.
But when deployed on IIS, it can only works when accessing the website by "https://localhost". But an error is thrown when accessing the website by "https://machinename".
AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '4e392b7a-####-####-####-####'.
2 urls are configured on the azure ad authentication:
https://machinename/
https://localhost/
The configuration in the file web.config:
<add key="ClientId" value="4e392b7a-####-####-####-############" />
<add key="Tenant" value="72f988bf-####-####-####-############" />
<add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />
<add key="RedirectUri" value="https://machinename/" />
<add key="PostLogoutRedirectUri" value="https://machinename/KeepAlive/SignOut" />

According to your error message, you must ensure that the reply URL in the Azure portal is exactly the same as the reply URL configured by the application.
I have answered similar questions before, There is a general solution to the problem of not match:
When you visit the application url , you will be redirected to the login page. Decode the authorization request URL, you will find redirect_uri, copy the value of redirect_uri and paste it into the azure portal, and try again.
Update:
Thanks for the solution provided by #Tom. For this error, you also need to add the port :
https://machinename/{port}
https://localhost/{port}

Related

Cannot login if requiressl is set to true

I have a live web site in IIS 7.5. I can login to my site correctly with http protocol till I add this line in Web.config:
httpCookies httpOnlyCookies="true" requireSSL="true"
All configuration for SSL is done but I cannot login anymore with both http and https although the cookie .ASPXAUTH is created.
If I set requireSSL="false", I can login normally.
Please help!
I had the same problem and as I came across this post searching for a solution I can explain what happened: your application was configure to use secure cookies and this requires the browser to issue the request over SSL. Therefore, if requireSSL attribute is set to true, you can't log in to your website with Http

MVC4 Windows Authentication Redirect to Account/Login

I am setting up Windows Authentication in an MVC 4 application using Visual Studio 2013 and using the IIS Express Development Server. However, I get redirected to /Account/Login (as if I were using forms authentication).
I have no reference to WebMatrix in my bin folder (or anywhere) as described here: ASP.NET MVC3 and Windows Auth on IIS keeps redirecting to /Account/Login.
I have added these entries to appSettings in the web.config as suggested by this post:
MVC5 Redirects to Login.aspx when using Windows Authentication
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
Here is what I have done so far:
Added windows authentication to system.web.
<authentication mode="Windows"/>
Added the [Authorize] attribute to my controller. I have also tried using the authorization tag in the web.config instead of the attribute on the controller (deny users="?"). The results are the same.
For the Development Server settings in my project I changed these settings:
Anonymous Authentication = Disabled
Windows Authentication = Enabled
I can find no reference to FormsAuthentication. I can't figure out why it still redirects to a non-existent login page.
When the project was created it may have been done using a template that added Startup.Auth in the App_Start folder in your project. (The default template uses Individual User Accounts if you did not change it to windows authentication as the Authentication method in the create new ASP.Net Project dialog)
Try commenting out these lines if they are present
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
Or if you have not added anything to this file you could remove it completely and the call to it
ConfigureAuth(app);
found in the startup.cs in the root of the project
Now most of the account controller is no good to use if this case so be prepared to clean that up also.
This line is important and correct in the web config
<authentication mode="Windows"/>
these lines are probably not directly related to the issue and can be removed
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>
The other development settings are also correct.

wfresh parameter causing ADFS login to fail

I am using ADFS to do federated logins with a number of different RPs, including our own custom web app, Office 365 and some other third-party services. I have run into a problem where logins silently fail when the wfresh=0 is specified in the URL. It just keeps asking for my password over and over again. When I click the "Login" button, it doesn't log you in and redirect you to back to the RP, nor does it fail and give you an error message. Instead, it redirects you back to the STS login page, so it looks to the user like it's silently failing.
I found this question: wfresh not working with WS-Federation via ADFS, which seems to be on the right track. However, while I am definitely seeing issues with integrated logins, I am getting similar issues with Forms logins as well. The outward symptoms are different, but the behavior seems to be the same: If you specify wfresh=0, it sends you directly to /adfs/ls.
Is there any way to configure ADFS to treat wfresh correctly, or at least to ignore it?
Update: Cross-posted to MSDN Geneva Forums: http://social.msdn.microsoft.com/Forums/vstudio/en-US/7acbbd11-cd69-466b-8faa-f129f24fe1fe/wfresh-parameter-causing-adfs-login-to-fail
Update: Microsoft today released their hotfix for this: http://support.microsoft.com/kb/2896713. It is not a public hotfix, so you will need to contact Microsoft support to get the update.
Previous: I spoke with an Escalation Engineer in Global Escalation Services for Microsoft. The EE said they are aware of this issue, tracking impacted customers, and working on a solution. Anyone who is experiencing this same problem should contact Microsoft support and open a support case so they are notified when the solution is available. Microsoft support is tracking this issue internally under solution id number 2879919.
I am seeing the same thing as of lately. We have connections with some RPs and also use Office 365. If I leave my machine logged into portal.microsoftonline.com it will eventually show "page cannot be displayed" with the URL showing the long string and "wfresh=0" at the end.
Externally, if i leave my browser logged into the portal it will take me back to the form but never accept my new credentials. If I change the value of "wfresh=0" to "1" it allows me back in external and internal. I'm trying to review event logs to see anything but have not found any clues. still looking.
Would it be a good or bad solution (if possible) to use MS IIS URL rewrite to replace or remove wfresh=0 from the URL when hitting the IIS?
Best would of course be if the default installation of ADFS worked with wfresh=0 in the first place :-)
IIS URL Rewrite1
Update:
My problem was that only internal clients experienced the error while external clients (using the ADFS proxy servers) did not.
With URL rewrite on the internal ADFS 2.1 servers and the following URL rewrite rule in /adfs/ls/web.config works:
<rule name="wfresh0to1" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{QUERY_STRING}" pattern="(.*)wfresh=0(.*)" />
</conditions>
<action type="Rewrite" url="{R:0}?{C:1}wfresh=1{C:2}" appendQueryString="false" />
</rule>

adfs windows authentication

I have tried searching for this and can't find anything.
I want users to have a true SSO experience. Meaning they login to their computer and when they hit a web app that we have set up trust with in ADFS they are taken straight to that website. Right now no matter what they are taken to the ADFS forms login page. We only want the forms login page to appear if the user is not already connected to the network. Otherwise, ADFS should recoginize that the user is on the network and use the windows authentication.
What do I have to change in ADFS to make this happen?
In ADFS web.config, what order do you have for:
<localAuthenticationTypes>
<add name="Integrated" page="auth/integrated/" />
<add name="Forms" page="FormsSignIn.aspx" />
<add name="TlsClient" page="auth/sslclient/" />
<add name="Basic" page="auth/basic/" />
</localAuthenticationTypes>
Is Forms on top?
Are these users on the internet or intranet?
Do you use an ADFS proxy?
One option is to add a handler for the RedirectingToIdentityProvider event by placing the code just below this paragraph in your global.asax. This gives you a chance to jump in before the browser is redirected to ADFS and modify what the request (query string) looks like. You can do this to specify authentication types, or home realms (if you have multiple federations and want to skip HRD), and probably a lot of other stuff I don't know about.
void Application_Init()
{
FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider += new EventHandler<RedirectingToIdentityProviderEventArgs>(WSFederationAuthentication_RedirectingToIdentityProvider);
}
Then you would add code to your handler that might look something like this:
void WSFederationAuthentication_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
WSFederationAuthenticationModule instance = FederatedAuthentication.WSFederationAuthenticationModule;
SignInRequestMessage request = instance.CreateSignInRequest(Guid.NewGuid().ToString(), instance.Realm, true);
request.AuthenticationType = "urn:federation:authentication:windows";
Response.Redirect(request.WriteQueryString());
}
When you set the request.AuthenticationType to that value, you're telling ADFS that you want to do windows (integrated) authentication. This was all that was required for me to get it to work. I didn't have to bother with switching the order of the authentication types in the web.config as nzpcmad suggested.
Also, for this to work, IIS and your web browser are working some magic outside of AD FS and your relying party, so in IE your users have to go to tools > Internet Options > Security and add the site to your Local Intranet sites. There's probably a way to push this out with group policies or something, but that's another question. Anyway, now that I think of it, this may be the only step you're missing.

Microsoft.IdentityModel: Key not valid for use in specified state

I have a claims aware web application using Windows Identity Foundation that has been working well, except on one server. I am seeing the error message shown below in the event log.
Exception information:
Exception type: CryptographicException
Exception message: Key not valid for use in specified state.
at System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope)
at Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[] encoded)
This application is using a very standard implemenation of WIF with ADFS v2. It is not using RsaEncryptionCookieTransform. I am looking for any suggestions on how to diagnose this. Things I have tried so far:
The Application Pool is using the ASP.NET v4.0 identity which has the "Load User Profile" setting set to true.
I deleted the C:\Users\ASP.NET v4.0\AppData folder and saw this was successfully recreated.
I checked permissions on certificate private keys, which were good. I also tried disabling token encryption which did not make any difference.
Any advice would be appreciated.
This is usually caused by the application not being able to decrypt the authentication token cookie. Make sure that the identity that owns the App Pool has sufficient permission to access your certificate store. Try changing the Identity to NetworkService and see if that helps.
You should also clear your browser's cookies to make sure you don't have cookies from a different application cached.
The issue is 100% reproducible:
Indeed, after application being re-deployed, AND old authentication cookie is left on the client machine (client did not sign out) -this error appears to the client on any following request.
To fix this error client either has to delete the cookies and/or sign-in then sign-out from STS. Once all done - the error goes away and everything is fine until next upgrade....
After some research, I think this is a bug in the SessionAuthenticationModule that needs to be fixed. If you carefully look at the stack trace above, there is an interesting method called TryReadSessionTokenFromCookie, which sets expectation that authentication module will "try" to read the token from cookie, and will return false if this fails -here is the code (thanks to Resharper!):
public bool TryReadSessionTokenFromCookie(out SessionSecurityToken sessionToken)
{
byte[] sessionCookie = this.CookieHandler.Read();
if (sessionCookie == null)
{
sessionToken = null;
return false;
}
sessionToken = this.ReadSessionTokenFromCookie(sessionCookie);
if (DiagnosticUtil.TraceUtil.ShouldTrace(TraceEventType.Verbose))
{
DiagnosticUtil.TraceUtil.Trace(TraceEventType.Verbose, TraceCode.Diagnostics, SR.GetString("TraceValidateToken", new object[0]), new TokenTraceRecord(sessionToken), null);
}
return true;
}
Obviously, the code fails in this method with unhandled error and developer is left without any option to handle the error in more or less reasonable way. (...Or at least I could not find any, since this HTTP module does not pass this error onto HttpApplication object for handling, and throws it in the user's face.)
So, I think there are two bugs:
1) Security token handler needs to be more specific on the reasoning of thrown ID1073 (server side decryption error or wrong (old) cookie error)
2) There has to be a way for a developer to handle this error and sign-out the user, if it occurs. I'll take ANY help on this one...
Can anyone PLEASE create a sample code, showing how to intercept this exception so user can be automatically signed-out when this error occurs? Again, Application.Error event does not seem to get fired from this module -not sure what else can be done to handle it, other than writing my own SessionAuthenticationModule.
ANY HELP IS HIGHLY APPRECIATED!!!
Thanks!
Alex
I resolve my case because i have the same cookie name "FedAuth" for two applications (this is the name by default). Just put a different name and it's resolve :
<system.identityModel.services>
<federationConfiguration>
<cookieHandler name="ACookieName" />
</federationConfiguration>
The following worked for me:
You need to add section to system.identityModel/identityConfiguration
Reference:
SessionSecurityTokenHandler trying to decrypt SessionSecurityToken in RSA-encrypted cookie using DPAPI; why?
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
<audienceUris>
<add value="yoursite.com" />
</audienceUris>
<issuerNameRegistry type="Thinktecture.IdentityModel.Tokens.MetadataBasedIssuerNameRegistry, Thinktecture.IdentityModel">
<trustedIssuerMetadata issuerName="urn:federation:company:stage" metadataAddress="https://federation-sts-stage.company.com/FederationMetadata/2007-06/FederationMetadata.xml"></trustedIssuerMetadata>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
<securityTokenHandlers>
<add type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,
System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</securityTokenHandlers>
</identityConfiguration>
</system.identityModel>
Deleting the FedAuth cookies might work. When the exception occurs, try this in the Application_Error method of the Global.asax file:
Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.SignOut();
This error doesn't seem to be caught by http application.
Please check out http://social.technet.microsoft.com/wiki/contents/articles/1898.aspx#Q1 instead.
This issue is because of insufficient permission.
The app pool should have ApplicationPoolIdentity Identity to make it work.
Goto your apppool -> Advanced Settings -> Build-in accounts to change the settings