Using Saml with Azure AD using Blazer Web assembly - azure-active-directory

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

Related

DefaultAzureCredential Failing for console app after redirect to localhost -localhost sent invalid response

I am using DefaultCredential to connect to build configuration from azure keyvault.
var secretClient = new SecretClient(new Uri($"https://{keyvaultName}.vault.azure.net/"),
new DefaultAzureCredential(true)
);
IConfigurationRoot configuration = null;
configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.AddAzureKeyVault(secretClient, new PrefixKeyVaultSecretManager(environment))
.AddUserSecrets<Program>().Build();
This was working earlier but now it is failing with interactive browser authentication.
After selecting account, it is redirecting back to localhost and throwing error ("localhost sent an invalid response")
I am using "Azure.Identity" Version="1.4.1" . I also tried with latest beta package(1.5.0-beta.4).
Also Azure.Security.KeyVault.Secrets" Version="4.2.0"
I was getting a similar error from a Windows app using interactive AzureAD authentication. It turned out to be the result of the localhost domain appearing in my Edge (and Chrome) HSTS policy cache. The Azure AD signin flow was trying to redirect to http://localhost:61425/?code=.... But because I had been developing an unrelated ASP.NET application on my machine that used the HSTS middleware (i.e. called app.UseHsts) my browser was remembering that policy and forcing the AzureAD signin redirect to https://localhost:61425/?code=.... That switch from http to https broke the redirect handling in my Windows app.
The solution was to delete the localhost domain from the browser's list of domain security policies.
In edge, type this in the address bar: edge://net-internals/#hsts
In Chrome: chrome://net-internals/#hsts
See ERR_SSL_PROTOCOL_ERROR for localhost from Visual Studio debug
Check your application's redirect URI at Azure Portal. You can find it under Authentication on your application's page.
Set the redirect URI to https://login.microsoftonline.com/common/oauth2/nativeclient.
More information about redirect URIs: https://learn.microsoft.com/en-us/azure/active-directory/develop/reply-url

AADSTS50011 after creating CNAME

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.

Blazor Client side get CORS error when accessing Azure Function using Azure Active directory

I've been trying to deploy my Blazor PWA for 2 days without any success so far, if someone has an idea of what I’m doing wrong I would be really grateful.
hello
I could resolve most of my issues by myself but I'm now stuck on a CORS problem using AAD.
Here's my project setup:
Blazor webassembly client hosted on Static Website Storage (works
great), Net 5
AzureFunctions connected to an Azure Sql Server database (works great
with anonymous authentication in Blazor)
Azure Active Directory I want to use to authenticate the users.
(protecting both the blazor app and the functions)
So I’ve created an App registration, added my static web site address as SPA uri and uncheck both implicit.
In my blazor client, program.cs, I’ve added the following code to connect to AAD:
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication); //contains clientId, Authority
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
options.ProviderOptions.LoginMode = "redirect";
});
That works great too, I can login, authorize view works as expected.
The problem is when I try to authenticate Azure functions with «Login with Azure Active Directory»,
I' tried with both express and advanced configurations (using clientId, tenantId) but when I
Access to fetch at 'https://login.windows.net/tenantid/oauth2/authorize ... (redirected from 'https://myfunctionstorage.azurewebsites.net/api/client/list') from origin 'https://*****9.web.core.windows.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have of course enabled CORS for my Blazor Client Address on Azure Functions configuration but the problem seems to be about the login windows uri...
Also, if I enable the token id implicit flow in the App registration and access the login url in the browser it works perfectly fine.
All the examples I could find so far are about msal 1.0 and App registration using implicit flow instead of SPA so it doesn't help...
Thank you for your time and your help.
UPDATE:
I’ve done more researches since yesterday and I think it could by related to my HTTPClient, currently I use the basic one (with just a base adress).
But I’ve seen on some example that when using the Client using AAD it needs more parameters, for example:
builder.Services.AddHttpClient("companiesAPI", cl => { cl.BaseAddress = new Uri("https://localhost:5001/api/"); }) .AddHttpMessageHandler(sp => { var handler = sp.GetService<AuthorizationMessageHandler>() .ConfigureHandler( authorizedUrls: new[] { "https://localhost:5001" }, scopes: new[] { "companyApi" } ); return handler; });
Is that AuthorizationMessageHandler needed ?
Also I see some references to the need of using the «use_impersonation» scope.
Are those changes (on HttpClient and the use_impersonation scope) also required when using msal2/SPA app registration ?
Thank you
If want to call the Azure function projected by Azure AD in Blazor webassembly client, please refer to the following steps
If you want to call Azure function projected by Azure AD in angular application, please refer to the following code
Create Azure AD application to protect function
Register Azure AD application. After doing that, please copy Application (client) ID and the Directory (tenant) ID
Configure Redirect URI. Select Web and type <app-url>/.auth/login/aad/callback.
Enable Implicit grant flow
Define API scope and copy it
Create client secret.
Enable Azure Active Directory in your App Service app
Configure CORS policy in Azure Function
Create Client AD application to access function
Register application
Enable Implicit grant flow
configure API permissions. Let your client application have permissions to access function
Code
Create Custom AuthorizationMessageHandler class
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { "<your function app url>" },
scopes: new[] { "<the function app API scope your define>" });
}
}
Add the following code in Program.cs.
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
// register CustomAuthorizationMessageHandler
builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
// configure httpclient
// call the following code please add packageMicrosoft.Extensions.Http 3.1.0
builder.Services.AddHttpClient("ServerAPI", client =>
client.BaseAddress = new Uri("<your function app url>"))
.AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
// register the httpclient
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("ServerAPI"));
// configure Azure AD auth
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("<the function app API scope your define>");
});
await builder.Build().RunAsync();
}
Call the API
#page "/fetchdata"
#using Microsoft.AspNetCore.Components.WebAssembly.Authentication
#inject HttpClient Http
<h1>Call Azure Function</h1>
<p>This component demonstrates fetching data from the server.</p>
<p>Result: #forecasts</p>
<button class="btn btn-primary" #onclick="CallFun">Call Function</button>
#code {
private string forecasts;
protected async Task CallFun()
{
forecasts = await Http.GetStringAsync("api/http");
}
}

IdentityServer4 oidc-client error - authority mismatch on settings vs. signin state

I have an IdentityServer4 and C# .NET Core web application behind an NGINX reverse proxy:
https://id.local.domain -> http://id-local
https://web.local.domain -> http://web-local
I can get to and enter my credentials on the ID4 login page, but after being redirected back to my /account/callback page from ID4, the following JavaScript error appears:
Error: authority mismatch on settings vs. signin state
Is this a problem with my oidc call, the NGINX + ID4 setup, or something else? I have tried using:
services.AddIdentityServer(options =>
{
options.PublicOrigin = "https://id.local.domain";
…
Is that the correct URL to enter? Do I need to use options.IssuerUri instead of/as well?
the identity server will not accept or allow clients only if the config sent from the clients match with its config
same Redirect Urls
same ClientID
same ClientRoot (client base url have to be allowed in 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

Resources