AADSTS50011 after creating CNAME - azure-active-directory

I had my IdenityServer4 oidc service running correctly as an AppService on Azure. Now I created a DNS entry in my hosting to create better names for all the services. For Azure-AD I keep getting this error:
AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: '<my app id>'.
I have these two reply-urls setup in Azure AD portal:
https://account.mysite.com/signin-microsoft
https://myapp-oidc.azurewebsites.net/signin-microsoft
The second one works but the first does not, giving the error. Is there any way for me to debug this and see what reply url apparently is different that the one configured?
Here's the setup in startup.cs:
services
.AddAuthentication()
.AddMicrosoftAccount("Microsoft", options => {
options.SignInScheme = "Identity.External";
options.ClientId = "xxx";
options.ClientSecret = "xxx";
})
I did the same for google (https://account.mysite.com/signin-google) and that worked right away but I can't get Azure to work on the new address.

Related

Get error "login.live.com page can’t be found" when invoking Azure Ad as external IDP in IdentitySrever4

I try to follow this tutorial to add Azure Ad as another external IDP for my IdentityServer4 service (I have gotten Windows and Google working already). I can get the "Azure Ad" button displayed on my IdentityServer login page now, but when I click on it, I get the following error returned:
Here is how I configured Azure Ad in ConfigureServices of my Startup class. I also tried replacing "aad" with "oidc", which is what I used and worked in Google, but no difference here.
and here is how my Azure Ad account configuration looks like. The colors match up with above indicating the values I use in my code:
Can someone tell me what I may be doing wrong here?
Initially please try by deleting history in the browser and use "login.microsoftonline.com/<tenantId>/v2.0/" as authority string.
And options.CallbackPath = "/signin-oidc"; options.ResponseType = "code id_token";
NOTE : The identity platform which is used by Microsoft has a character limit for links. This type of error will appear if the authorization request or link is longer than the said limit,.
Protocols like OpenID Connect, allow state as a parameter in the authorization request, and the identity provider will return that state in the response as you can find that in error page you provided .
Because of which the request URL becomes large as sometimes the state parameter is long.(which might be the possible case here)
Try to call the AddOidcStateDataFormatterCache extension method on the IServiceCollection in startup class which uses the distributed cache in the backend like:
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients())
.AddTestUsers(Config.GetUsers());
services.AddAuthentication()
.AddOpenIdConnect("aad", "Azure AD", options =>
{
// ...
})
you can write the way as below :
services.AddOidcStateDataFormatterCache(); //Add this line
services.AddAuthentication()
.AddOpenIdConnect("aad", "Azure AD", options =>
{
// ...
})
You may check these similar References for more details :
Sign-in with External Identity Providers — IdentityServer4 1.0.0 documentation
(Or)
See section : 22.4 Handling the callback and signing in the user in IdentityServer4 Documentation
At least check for dns or firewall issues .

How to use Azure AppRoles in Blazor Server with Azure Active Directory

I have an up and running .NET 5 Web-API with a Blazor Server Client in Production. I'd like to switch from Individual User Accounts to Azure AD using App Roles to authenticate specific Users in my Controllers. I found lots of Information regarding Webassembly but none for Blazor Server.
Has somebody a working Solution for a .NET 5/6 Web-Api with a Blazor Server Client and integrating Azure App Roles?
Apps are already registered in the Azure Portal and so forth, I just need to know how to pass the App Roles specific stuff to my API, so my Controller can work with the [Authorize("Admin")] stuff. I suspect it will use Bearer Tokens aswell.
Edit:
Thanks a lot for reading. So I figured out that if I use something like this in my Controller only using the [Authorize] Attribute without any roles:
var identities = HttpContext.User.Identities.ToList();
foreach (var item in identities)
{
if (item.RoleClaimType == "admin")
{
// return or do something
}
}
It would just work fine but there has to be some smoother solution for this or am I doing this completly wrong? When I look at the WASM Samples, they pick up the AppRoles with their token and the Controller simply can use the [Authorize(Roles = "xyz")] Attribute. What am I missing here? :/
Btw, this is how my Program.cs looks right now:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.TokenValidationParameters.RoleClaimType =
"admin";
options.TokenValidationParameters.RoleClaimType = "doku";
},
options => { builder.Configuration.Bind("AzureAd", options); });
Thank you guys/gals <3
Please check if the given references are of use in your case.
A SERVER API app can authorize users to access secure API endpoints with authorization policies for security groups, AAD Administrator Roles, and App Roles
In Program.cs of a SERVER app, specify the claim as roleclaim
example:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAd", options);
options.TokenValidationParameters.RoleClaimType =
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
},
options => { Configuration.Bind("AzureAd", options); });
Then you can use admin role on authorization controller to access
[Authorize(Roles = "admin")]
Here in App roles section you can see the configuration for both
server and client.
Edit the app role in the manifest editor in portal and then give
proper api permissions , expose scopes and grant permission for admin
consent >see Add app roles and get them from a token .And the
procedural logic must contain those scopes required by api.
Note : The appRoles manifest property of both the client and the
server Azure portal app registrations must include the same configured
roles.
Please check this for more detailed information which guides for both server and client apps.
Other references:
using-app-roles-with-AAD-blazor-server-client scenario | codemaze.com
quickstart-configure-app-expose-web-apis
quickstart-configure-app-access-web-apis

Using Saml with Azure AD using Blazer Web assembly

I'm trying to use .NET core Blazer webAssembly client UI from main() and authenticate with Azure AD using SAML with the following code, but getting error. can't figure this out one issue below. any clue is appreciated
there was an error trying to log you in: 'Cannot read property 'redirectUri' of undefined'
OIDC works fine.
Below is my code called from Main in Program.cs
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddHttpClient("BlazorWASMAuthApp.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("BlazorWASMAuthApp.ServerAPI"));
builder.Services.AddApiAuthorization(); builder.Services.AddAuthenticationCore(); builder.Services.AddAuthorizationCore();
builder.Services.AddAuthentication().AddSaml2(options =>
{
// builder.Configuration.Bind("AzureAd", options.SPOptions.AuthenticateRequestSigningBehavior);
//APP Registration keys Will be moved to Json in subsequent story
options.SPOptions.EntityId = new EntityId("https://localhost:5001/saml2");
//options.SPOptions..Add("https://localhost:5001/saml2/API.Access");
options.IdentityProviders.Add(
new IdentityProvider(
new EntityId("https://sts.windows.net/{Clientid}/"), options.SPOptions)
{
//SingleSignOnServiceUrl = signinURI,
MetadataLocation = ...federationdataxml?clientid={clientid}"
});
;
})
.AddCookie();
The most common errors as per ms docs are caused by incorrect configuration
Depending on the requirements of the scenario, a missing or incorrect
Authority, Instance, Tenant ID, Tenant domain, Client ID, or Redirect
URI prevents an app from authenticating clients.
Running the app at a different port than is configured in the Redirect
URI of the Identity Provider's app registration.
Please check if the cause is missing return url parameter in configuration in your code provided:
options.SPOptions.ReturnUrl = new Uri("https://localhost:5001/authentication/azurecallback"); which comes after
options.SPOptions.EntityId = new EntityId("https://localhost:5001/saml2");
else check Portal side configurations.
While registering API , redirect uri is set as web and its field is left empty and api is exposed from Expose api .
But When registering client app , redirect uri must be set ,hope you have done so.
client app > go active directory b2c >give name >select supported account>redirect uri >select SPA-give redirect ur like https://localhost:5001/authentication/login-callback
(format of uri : https://localhost:{PORT}/authentication/login-callback.)
This 'authentication/login-callback' must be present in your code configuration too.
From reference
NOTE: The default port for an app running on Kestrel is 5001. If the
app is run on a different Kestrel port, use the app's port. For IIS
Express, the randomly generated port for the app can be found in the
Server app's properties in the Debug panel. Since the app doesn't
exist at this point and the IIS Express port isn't known, return to
this step after the app is created and update the redirect URI. A
remark appears in the Create the app section to remind IIS Express
users to update the redirect URI.
So Check the port running and update the redirect uri if not done.
References:
Reference 1
Reference 2
Cors

AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application: '<AppId>'

I have a .NET Core 2 app template that is configured to use Azure AD out of the box.
The configuration is:
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "lautaroarinolive.onmicrosoft.com",
"TenantId": "67cb2dfd-ebd5-40d8-829b-378340981a17",
"ClientId": "50819a7a-e018-4c1d-bf0a-18c8fce5c600",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
In my portal, I have an Azure app registration with the same id as ClientId. It has the reply URL [APP-URL]/signin-oidc.
The localhost app works only if I set the reply URL to [LocalhostURL]/signin-oidc, even though I've learned that the configuration should not affect log in on localhost.
The Azure app does not work in any case.
In both apps when it doesn't work I get this error:
AADSTS50011: The reply url specified in the request does not match the
reply urls configured for the application:
'50819a7a-e018-4c1d-bf0a-18c8fce5c600'
Is it correct that a localhost app should not need a configured reply URL?
Why do I get the "reply url not configured" error?
You can refer to this Sample to rebuild your .NET core App and publish to the Azure.
There are some NOTES you need to pay attention to :
you need to change the port from 5000 to the effective one. Currently, it should be 61659. So, when you do a test in your localhost, you can set the reply URL in the AAD App with http://localhost:61659/signin-oidc
Update these URLs if you configure the app for production use or If you publish the App to Azure Web App, you should change the Reply URL in both App config file and AAD Application to be <AppURL>/signin-oidc
For example, https://www.contoso.com/signin-oidc or https://Myapp.azurewebsites.net/signout-oidc.
I had a similar problem with a .NET 4.6.1 web application.
I had to configure the Reply URL for my app in azure similar to the accepted answer, however the callback url was different.
Select Azure Active Directory -> App Registrations -> <your app>
Select Settings -> Reply URLs
Add your apps URL + '/.auth/login/aad/callback'
For Example:
https://somesite.azurewebsites.net/.auth/login/aad/callback
Check your redirect uri in your Microsoft sign in page
redirect_uri=https://localhost:8443/login&response_type=code&scope=openid%20profile&state=7GsiHb
And make sure that you have added the same URI to redirect URI list in your registered application (Active Directory -> App Registration -> Your Application). As mentioned in other answers may need to change supported account type as "Multiple Organizations".
Just got the same error. My app is a .NET 5 ASP.NET Core app running in a Linux docker container inside of a web app. Troubleshooting using Fiddler has shown that in calls to login.microsoft.com the value of a redirect_uri query string variable was starting with "http://" and not with "https://" as I would expect despite my attempts to enforce TLS-only on the web app itself. That led to URL mismatch and to the error AADSTS50011.
Setting the environment variable ASPNETCORE_FORWARDEDHEADERS_ENABLED=true on the web app has fixed the issue. Microsoft has documented it here: https://devblogs.microsoft.com/aspnet/forwarded-headers-middleware-updates-in-net-core-3-0-preview-6/
Make sure services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); must below the Authentication configuration.
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "";
options.ClientId = "";
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "";
options.SignedOutRedirectUri = "";
options.TokenValidationParameters.NameClaimType = "name";
})
.AddCookie();
I was facing the same error due to having added AddMvc() before the AddAuthentication() extension method.
In some case, azure to use the 'www' on the url, even if you especific the url on the portal without 'www'. Use "https://www.mysite.co/signin-oidc" instead "https://mysite.co/signin-oidc" in your redirectUri variable.
Small thing, but at the Web Tenant, at custom domains settings HTTPS Only option should be turned on depending on URLs used by the site. I had the same problem, as at the login, the redrect_uri=http://sitename was concatenated instead of https. Enabling this option resolved my authentication issue.
If you are signing in from AAD you should use app-base-url/sigin-aad.
If you use React- Native. Able to check the web portal: https://portal.azure.com/.
iOS: {YOUR_BUNDLE_IDENTIFIER}://{YOUR_BUNDLE_IDENTIFIER}/ios/callback
Android: {YOUR_APP_PACKAGE_NAME}://{YOUR_APP_PACKAGE_NAME}/android/callback
pls refer with image below.
enter image description here
The only solution for me: in the Azure portal https://portal.azure.com, navigate to "app registrations" -> select your application -> "authentication" from the left sidebar menu -> "mobile and desktop applications" redirect URIs -> and click "Add URI" -> type the following
ms-appx-web://microsoft.aad.brokerplugin/{Your_Application's_Client_ID}
Example: ms-appx-web://microsoft.aad.brokerplugin/5r3257qe-7jci-3501-38k0-3791h90542m7

How do you authenticate AAD B2C using MSAL?

I have a working version of a Client/Server authentication using ADAL. However, it appears that the B2C AAD doesn't work well with ADAL when you want to use Local Accounts (that is, just a username or just an email address with no backing authenticator other than AAD). It appears the API we should be using for Local Accounts is the alpha release of MSAL. So far, so good. I'm able to create a local user using the Graph API and using the following code, I appear to be authenticating the local user 'joeconsumer#mycompany.com':
this.pca = new PublicClientApplication("a4828eaa-42f6-418a-8062-f857130b69ce");
AuthenticationResult result = await this.pca.AcquireTokenAsync(
new string[] { "a4828eaa-42f6-418a-8062-f857130b69ce" },
string.Empty,
UiOptions.ForceLogin,
null,
null,
"https://login.microsoftonline.com/" + "darkbondpublic.onmicrosoft.com",
"B2C_1_sign-in");
The problem is that I pass the security token from 'result.Token' back to the server using a custom security token mechanism in WCF. The code on the server, which used to work with ADAL, no longer seems to accept the security token from the above call:
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
Microsoft.IdentityModel.Tokens.SecurityToken securityToken = null;
ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(userName, this.GetTokenValidationParameters(MetadataAddress), out securityToken);
Thread.CurrentPrincipal = claimsPrincipal;
The error message is:
Can anyone tell me what is going on here? Do I need a different method of authenticating on the server?
The metadata endpoint you config for Azure AD B2C tenant is incorrect. Here is the correct one for your reference:
https://login.microsoftonline.com/{tenantId}/v2.0/.well-known/openid-configuration?p=B2C_1_Sign_In
We can find the metadata for the specific policy from the new Azure portal like figure below.
And in the metadata should able to see the keys endpoint like below:
https://login.microsoftonline.com/{tenant}/discovery/v2.0/keys?p={policy}
We can find the key with kid gfIKIH-yZ3phRHRyjnsHIqZMaePLGAELzPat0CNY4sA like below figure:
I think the problem is: you are sending request to V1 endpoint but AAD B2C uses V2 endpoint with the authority: https://login.microsoftonline.com/tfp/{tenantId}/{policyName}/v2.0/
Metadata for v2 endpoint is available at https://login.microsoftonline.com/tfp/{tenantId}/{policyName}/.well-known/openid-configuration
Can you update your Urls and make one more attempt?
To see an authority in Azure Portal select your policy, then:
Locate your Policy
Click "Edit"
Click "Token, session & SSO config"
Expand "Issuer (iss) claim"
Azure (uses V1 endpoint) and Azure AD B2C (uses V2 endpoint) use different set of keys to sign tokens, therefore it is important to download public keys from the right location - originally you downloaded it from V1 but instead need to use V2.
For me this endpoint worked:
https://{Azure domain}/{Azure tenant}/v2.0/.well-known/openid-configuration?p={Azure policy}

Resources