I'm implementing my own identity provider based on Thinktecture code. Here is a strange behaviour of Azure ACS while using a single sign-out feature, it differ for google/live and for my own identity provider.
URL for sign-out (realm is really same as a site name):
mysite.accesscontrol.windows.net/v2/wsfederation?wa=wsignout1.0&wreply=http%3a%2f%2flocalhost%2fAdministration.Frontend.Web%2f&wtrealm=http%3a%2f%2flocalhost%2fAdministration.Frontend.Web%2f
Here is a pseudo-code for logout:
//clear FedAuth cookies
FormsAuthentication.SignOut();
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
//call Single SignOut
var signoutRequestMessage = new SignOutRequestMessage(new Uri(signOutUrl));
return Redirect(signoutRequestMessage.WriteQueryString());
Here is sample flow (i'm using private browsing plus Fiddler to see everything):
1) I'm logging into my application with google account.
2) click a logout, in result i get a page on ACS with a this code:
function on_completion()
{window.location = 'http://localhost/Administration.Frontend.Web/';}
<iframe src="https://www.google.com/accounts/Logout" style="visibility: hidden"">/iframe>
<iframe src="http://localhost/Administration.Frontend.Web/?wa=wsignoutcleanup1.0" style="visibility: hidden"></iframe>
Result: i'm logged out from my application and google.
3) Log to my identity provider, click logout, redirected to same URL on ACS as on previous step but now i get 302 result with redirecting to
https://localhost/IdentityProvider/issue/wsfed?wa=wsignout1.0&wreply=https%3a%2f%2fmysite.accesscontrol.windows.net%2fv2%2fwsfederation%3fredirectUrl%3dhttp%3a%2f%2flocalhost%2fAdministration.Frontend.Web%2f
Result: i'm logged out from my application and my identity provider.
4) try to use google again, sucessfully login by entering credential, but logout if failed. I'm logged out from application but not logged from google. And also i see that i don't get page with iframe but instead ACS again try to redirect me to
https://localhost/IdentityProvider/issue/wsfed?wa=wsignout1.0
(and then back to mysite.accesscontrol.windows.net and finally to my application)
Two main question:
Why calling ACS logout give me iframe page with additional
wa=wsignoutcleanup1.0 for google/live but 302 redirect to my
identity provider, may be i miss something in
FederationMetadata.xml?
It looks like ACS after step 3 don't
understand that i successfully logged out from my identity provider
and from this moment try to do it again and again, how to tell them
to stop it?
Here is what you have to do.
First of all, when working with federated authentication always use HTTPS! Sometime protocol negotiations will fail just because it is plain HTTP. Sometimes browsers will block non-secure traffic, which is crucial for the sign-out process. So, always use HTTPS!
Now, to implement the form of single sign out you want you have do some more work.
Your URL for sign-out:
mysite.accesscontrol.windows.net/v2/wsfederation?wa=wsignout1.0&wreply=http%3a%2f%2flocalhost%2fAdministration.Frontend.Web%2f&wtrealm=http%3a%2f%2flocalhost%2fAdministration.Frontend.Web%2f
Do not use it as a parameter to construct SignOutRequestMessage. Use it to directly return Redirect(signOutUrl)!
You have to implement sign-out in two major places!
First place is your general logOff action method (given you are using MVC) Something similar to what you already have but with an important change:
FormsAuthentication.SignOut();
var signoutProtocolLocation = "https://[your_acs_namespace].accesscontrol.windows.net:443/v2/wsfederation?wa=wsignout1.0&wtrealm=[realm]&wreply=[reply]";
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(signoutProtocolLocation);
Note that here I use the overload with string paramer` to redirect result to ACS SSO location!
Now that very ACS SSO location will generate the above mentioned HTML page with JS and couple of iframe elements. One of them will be something like:
<iframe src="http://localhost/Administration.Frontend.Web/?wa=wsignoutcleanup1.0" style="visibility: hidden"></iframe>
Now that particular location http://localhost/Administration.Frontend.Web/?wa=wsignoutcleanup1.0 is the second place in your code where you have implement the SSO. This request must not redirect to a login page, but must instead process correctly and return 200 or 301 response (which in turn will return 200!)! For the sake of simplicity I will only paste the code used here:
if(Request.QueryString.AllKeys.Contains("wa")
&& Request.QueryString["wa"].Equals("wsignoutcleanup1.0"))
{
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
return RedirectToAction("Index");
}
It is really important that you only call the SignOut(true) overload with true when it is request for wsignoutcleanup action. And not when you do general log-off of users.
Please try all mentioned changes and let me know if it solves your issue!
Related
I have a React SPA which uses msal. I have configured Azure AD as Identity Provider for my AADB2C. I can signIn/signOut and other operations.
If my user signs out off my application, I want to also sign out of my Identity Provider. I looked a bit into this matter 1, 2, 3, 4, 5.
At this moment, I use msal's logoutRedirect method.
const url = new URL(AadEndSessionEndpoint);
url.searchParams.append('post_logout_redirect_uri', SPAUrl);
instance.logoutRedirect({
postLogoutRedirectUri: url.toString()
});
What happens, after my user signs out of my AADB2C, he gets redirected to the AAD end_session_endpoint. I can sign out there as well, but my user gets stuck there. Even though I'm passing the post_logout_redirect_uri query parameter to go back to my app, it ignores it.
How could I make this work?
You are doing an RP Initiated Logout in OpenID Connect terms, meaning you need to also send the id_token_hint query parameter.
I can also confirm that sending both query string parameters logs out successfully for my Azure developer account:
url.searchParams.append('post_logout_redirect_uri', SPAUrl);
url.searchParams.append('id_token_hint', myIdToken);
I think the MSAL library requires you to use getAccount instead:
const account = msalInstance.getAccount();
await msalInstance.logoutRedirect({
account,
postLogoutRedirectUri: "https://contoso.com/loggedOut"
});
UPDATE
Your code above is not right - the post logout redirect URI should be that of your own app - I expect the library already knows the end session endpoint location - so just do this:
instance.logoutRedirect({
postLogoutRedirectUri: SPAUrl
});
At the same time it is worth being aware that the full standards based GET URL should look like this. With the knowledge of the expected URL you can check that you are sending the right request via browser tools:
https://[AadEndSessionEndpoint]?id_token_hint=[myIdToken]&post_logout_redirect_uri=[SPAUrl]
The end session endpoint should be a value such as this by the way:
https://login.microsoftonline.com/7f071fbc-8bf2-4e61-bb48-dabd8e2f5b5a/oauth2/v2.0/logout
I have a Blazor Hosted WASM application, and am using Azure AD-B2C to secure it. If a user who is not logged in tries to access any site on the page, they are directed to our b2c login page, as they should be, and if they supply a good username and password they are allowed to view the site. So far so good. However, if the user clicks on "Sign up now", and then cancels the signup process instead of providing a new username, password, and e-mail address, then they are redirected to the site's landing page (as if they had provided a good username and password), which fails to redirect them back to the b2c login page and produces a console message reading "info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user"
The documentation suggests that I access the app's manifest and set the allowPublicClient attribute to null or true to address this problem. I have done this, and the problem persists. Why isn't the user being redirected back to the B2C login page in this case, when they normally would be if they try to access any page on the site (including this landing page) in other cases?
When the user cancels and get redirected back to the landing page, it returns an specific error code in the url (eg: AADB2C90118) in the return redirect url (In some cases it only flashes quickly because Angular removes the query string after the redirect).
You need to listen to this and handle it. You can handle it manually by parsing the return url but if you use msal.js on client side you can listen to this and start the reset password flow.
this.broadcastService.subscribe("msal:loginFailure", (error) => {
console.warn("msal:loginFailure", error);
// Check for forgot password error
// Learn more about AAD error codes at https://learn.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes
if (error.errorMessage.indexOf("AADB2C90118") > -1) {
alreadyRedirecting = true;
this.msalAuthService.loginRedirect(
b2cPolicies.authorities.resetPassword
);
}
});
The above example is for when the user clicks on forgot password link and get redirected back, so you will need to find the error code that applies to you.
I have a bare-bones website (single page app) that tries to log in the user with AAD using the msal JavaScript library. It is practically just doing what the example AAD login code does:
It creates a UserAgentApplication with my app's client ID and the authority URL for my tenant
It calls handleRedirectCallback and loginRedirect
It tries to get either the accessToken or the errorCode/errorMessage from the redirect response
Under practically all circumstances this works fine. Users visit my page, they get redirected and login just fine. One particular user, however, after the redirect and attempt to login gets this error:
Login failed: invalid_client - AADSTS650051: The parameter 'dynamicPermissions' in the request payload is not a valid parameter for the function import 'consentToApp'.
Trace Id: ed33266a-26ac-4706-9018-e6e89f650100
Correlation Id: e3103cab-1a7f-4a99-8455-fd8c8a769e35
Timestamp: 2019-06-25 20:50:44Z
He has tried this in many different browser (Edge/Chrome) and always gets this error, even in InPrivate/Incognito mode. No other user ever runs into error that I've found.
I'm not sure how to debug the issue because in my code I don't ever specify a 'dynamicPermissons' property or reference a function named 'consentToApp.'
How can I troubleshoot what is causing this error for this one user?
Thanks!
Ultimately this turned out to be a bug in the AAD service that was fixed by Microsoft.
I have registered the app in Azure AAD with reply urls. Enable id_token and auth token. If i give the exact url as the parameter it works fine. but if I add the query string as a parameter in reply url it is not working and throws error
AADSTS50011: The reply url specified in the request does not match the
reply urls configured for the application: ''.
Below is my sample URL format generated by ADAL.js file.
https://login.microsoftonline.com/.onmicrosoft.com/oauth2/authorize
?response_type=id_token &client_id=
&redirect_uri=?p1=123&p2=456
&state=62439108-d296-4a0d-91cc-4f6580656e83
&client-request-id=1a5ad90a-26fc-4e60-bbcc-8d58bbbcc1f7
&x-client-SKU=Js &x-client-Ver=1.0.13
&nonce=a4a6215c-0706-4fbc-91a9-36e4cd3a262e
If i remove this ?p1=123&p2=456 query string from the redirect_url, it works fine. The other workaround i see is if i go to legacy app registration and add "" at the end of the url it is working. But the new app registration does not allow "" in the reply_url while registration.
Anyone else also faced the same issue and fixed without adding "*" in the reply_url registration? please let me know.
This is an issue with ADAL.js (and MSAL.js) setting the redirect URI to the current URL by default.
You can get around it with an approach like this:
Set redirect URI as window.location.origin + "/aad-callback" (or anything else)
When requiring login, store current URL in sessionStorage (or local storage or a cookie)
Trigger login redirect
When your app gets a callback to /aad-callback, handle the tokens from the URL fragment
Load the local redirect URL from sessionStorage
Redirect user there
I wrote an article related to this but for MSAL.js: https://joonasw.net/view/avoiding-wildcard-reply-urls-with-msal-js.
The concepts are the same for ADAL.js.
We have a SaaS web app and our clients are requiring SSO authentication for each of them. We are using AzureADB2C and it works great, but now are looking at adding SSO.
I put in the SSO setup into the B2C tenet and it works great, but really messed up our login screen with a "MyCompanySSO" button to log in with, on our customer-facing login screen.
So now my idea is to have a separate user flow that handles each SSO setup. Starting with us. We'd go to MyCompany.OurSaaSApp.us and that'd forward them directly to the user flow endpoint and prompt them to login with their SSO account (AzureAD).
This all seems to try to work, but I'm getting these errors within the AzureADB2C middleware:
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Warning: .AspNetCore.Correlation. state property not found.
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler:Information: Error from RemoteAuthentication: Correlation failed..
Then I get pumped out onto a error page and the login fails.
So 2 things...
1.) Am I going in the right direction knowing what we're wanting to accomplish
2.) What do we need to do to resolve this?
Thanks everyone for the help, it's been greatly appreciated.
(note:)
Just to reiterate. The SSO works properly when the custom identity provider is attached to the existing SignUpOrIn UserFlow I have configured in the app. I'm only getting this error when I try to use another UserFlow that I want to use specifically for this SSO.
I'm not sure about that specific error, although "state" parameter is a parameter that your app sends in the request that will be returned in the token for correlation purposes.
Using and different policy for each federation sounds like the right approach, but if you are doing from a single instance of your app, you'll need to modify the OIDC protocol message with the correct authority (ie policy) on redirect.
In your OIDC middleware configuration, set up a handler for the RedirectToIdentityProvider notification. Then handle it with something like:
private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
//var policy = notification.OwinContext.Get<string>("Policy");
var tenantSegment = notification.Request.Path.Value.Split(new char [] { '/'}, StringSplitOptions.RemoveEmptyEntries)[0];
if (!string.IsNullOrEmpty(tenantSegment) && !tenantSegment.Equals(DefaultPolicy))
{
notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower().Replace(DefaultPolicy.ToLower(), $"B2C_1A_{tenantSegment.ToLower()}_SignUpSignInPolicy");
}
return Task.FromResult(0);
}
If you need to inject anything else tenant-related, that would be the place to do it.