Configuring an Azure Static Web App to authenticate using Azure AD B2C - azure

I've built a basic Vue web app using Azure Static Web Apps, and I'm trying to configure custom authentication. I've already managed to get everything (mostly) working using Auth0 by following the documentation and referencing this handy blog post.
For Auth0, I added AUTH0_ID=<my-auth0-id> and AUTH0_SECRET=<my-auth0-secret> to the local.settings.json file. My staticwebapp.config.json looked like this:
...
"auth": {
"identityProviders": {
"customOpenIdConnectProviders": {
"auth0": {
"registration": {
"clientIdSettingName": "AUTH0_ID",
"clientCredential": {
"clientSecretSettingName": "AUTH0_SECRET"
},
"openIdConnectConfiguration": {
"wellKnownOpenIdConfiguration": "https://<my-auth0-tenant>/.well-known/openid-configuration"
}
},
"login": {
"nameClaimType": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"scopes": ["openid", "profile"]
}
}
}
}
}
I'm now trying to set up authentication using Azure AD B2C. My understanding is that Azure Static Web Apps handles a portion of the authentication such that I should configure the ID provider to work with a web app rather than with a single page app framework. This is what I did when using Auth0 and it seemed to work.
I've added AADB2C_ID=<my-azure-ad-b2c-id> and AADB2C_SECRET=<my-azure-ad-b2c-secret> to the local.settings.json file. In staticwebapp.config.json I replaced ClientIdSettingName to AADB2C_ID, clientSecretSettingName to AADB2C_SECRET, and wellKnownOpenIdConfiguration to https://<my-azure-ad-b2>.b2clogin.com/<my-azure-ad-b2c>.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_signupsignin1. This references the 'signupsignin' user flow on my B2C tenant.
At this point I can visit /login which points to /.auth/login/aadb2c, initiates the user flow, and lets me sign up and verify as expected. The test user is then created in my Azure AD B2C tenant. However, B2C then tries to redirect me to /.auth/complete which throws a 403 error:
We need an email address or a handle from your login service. To use
this login, please update your account with the missing info.
I've tried adding /.auth/complete as an allowed redirect URI in Azure AD B2C but this doesn't fix things. What am I missing here?

Try changing to this: "nameClaimType": "emails".
Sourced from staticwebapp.config.json in here: https://github.com/Azure/static-web-apps/issues/457

Related

Microsoft.IdentityModel does not support a B2C issuer with 'tfp' in the URI

I am trying to run the WebApp B2C sample:
https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/1-WebApp-OIDC/1-5-B2C
When I try to login, I get the following error:
IDX40002: Microsoft.IdentityModel does not support a B2C issuer with 'tfp' in the URI. See https://aka.ms/ms-id-web/b2c-issuer for details.
If I edit the Instance to https://myHost.b2clogin.com I get:
AADSTS50011: The redirect URI 'https://myHost.b2clogin.com/1c2009bb-7e35-4a0e-9f22-xxxxxxxxx/oauth2/authresp' specified in the request does not match the redirect URIs configured for the application 'c24b0337-0bd9-45ee-8376-xxxxxxxxx'. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this.
Edit:
These are my redirects:
I tried to reproduce the same in my environment and got the below results:
I deployed custom policy starter pack via IEF Setup App by entering my Azure B2C tenant name like below:
When I checked that in Portal, custom policies are created successfully like below:
Now I registered one Azure AD B2C app named webapp1 as below:
I added redirect Uri to the above application like below: https://localhost:44316/signin-oidc
Now, I followed the same link that you mentioned and deployed one sample B2C web application by modifying appsettings.json file like below:
"AzureAdB2C": {
"Instance": "https://sridevib2c.b2clogin.com",
"ClientId": "9986e76d-bxx7-4x6x-bxx7-3d8xxxxx9a45",
"Domain": "sridevib2c.onmicrosoft.com",
"SignedOutCallbackPath": "/signout/B2C_1A_SIGNUP_SIGNIN",
"SignUpSignInPolicyId": "B2C_1A_SIGNUP_SIGNIN",
"ResetPasswordPolicyId": "B2C_1A_PASSWORDRESET",
"EditProfilePolicyId": "B2C_1A_PROFILEEDIT" // Optional profile editing policy
//"CallbackPath": "/signin/B2C_1A_SIGNUP_SIGNIN" // defaults to /signin-oidc
},
JSON file:
When I ran the above web application, it took me to below web page:
After selecting Sign Up/In, I got the login screen like below:
When I entered my credentials, I logged in to the application successfully like below:
When I clicked on Sign Out, it showed me below screen by signing me out:
After a long research I found this article/sample, where the Microsoft.Identity.UI framework is replaced with the Microsoft.AspNetCore.Authentication.AzureADB2C.UI.
However, with the https://myDomain.b2clogin.com url I still get the same error, using the custom domain it works, that's enough for me.

How to configure the ITfoxtec sample application "TestWebAppCore" with Azure AD as IdP

I'm trying to adapt the configuration of the ITfoxtec sample application TestWebAppCore from
https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/tree/master/test/TestWebAppCore
to use a SAML-configured Enterprise Application on Azure AD.
In appsettings.json I configured "IdPMetadata" with the metadata URL for the Enterrise Application in Azure AD, of this kind: "https://login.microsoftonline.com/9...3/federationmetadata/2007-06/federationmetadata.xml?appid=c..."
and I have not changed the other lines:
"SignatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
"SigningCertificateFile": "itfoxtec.identity.saml2.testwebappcore_Certificate.pfx",
"SigningCertificatePassword": "!QAZ2wsx",
//"SignatureValidationCertificateFile": "xxx.cer",
"CertificateValidationMode": "None", // "ChainTrust"
"RevocationMode": "NoCheck"
What are the "right" configuration that must be applied in the sample web app and on the Azure AD SAML configuration panel "Azure AD-side" ? In Azure AD SAML specially for the configuration items:
Reply URL (Assertion Consumer Service URL), I tried "https://localhost:44306/"
and
Sign on URL: I tried "https://localhost:44306/Auth/AssertionConsumerService"
but also after a "Login" (with my Azure credentials) the "users Claims" are not visible in the Home Page of the web application.
Thanks all.
Now I have fixed my implementation of the "TestWebAppCore" sample in ITfoxtec.Identity.Saml2.
These are the settings in the Azure AD administration console:
Identifier (Entity ID): itfoxtec-testwebappcore
Reply URL (Assertion Consumer Service URL):
https://localhost:44306/Auth/AssertionConsumerService
Sign on URL, Relay State and Logout Url not configured.
And these are the configurations in appsettings.json:
"Saml2": {
"IdPMetadata": "https://login.microsoftonline.com/9...3/federationmetadata/2007-06/federationmetadata.xml?appid=c...8",
"Issuer": "itfoxtec-testwebappcore",
"SingleSignOnDestination": "https://login.microsoftonline.com/9...3/saml2",
"SingleLogoutDestination": "https://login.microsoftonline.com/9...3/saml2",
"SignatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
"SigningCertificateFile": "itfoxtec.identity.saml2.testwebappcore_Certificate.pfx",
"SigningCertificatePassword": "!QAZ2wsx",
"CertificateValidationMode": "None", // "ChainTrust"
"RevocationMode": "NoCheck"
}
I compiled with .NET 5.0.
Note that in AuthController.cs I have commented the line
NameIdPolicy = new NameIdPolicy { AllowCreate = true, Format = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" },
otherwise the user name presented in the "Secure" page is an ID (in "persistent" format) and not the username with email. As an alternative it is possible to change the line with this one:
NameIdPolicy = new NameIdPolicy { AllowCreate = true, Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" },
Another good example that use the same ITfoxtex SAML identity library is this one:
https://github.com/nickgamb/Okta_SAML_Example (see also the article https://developer.okta.com/blog/2020/10/23/how-to-authenticate-with-saml-in-aspnet-core-and-csharp).

Azure OAuth authentication failed to redirect after successful authentication with Azure AD

I have .net core mvc application. I have implemented OAuth authentication with Azure AD for my web app.
From localhost it is working good as expected, but from Azure WebApp its failing to redirect to path after successful OAuth authentication.
FYI, I am accessing the application via AppGateway
I am using following code block for making OAuth Authentication.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
appsettings.json:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
"ClientId": "567f20e2-eb4f-4a1b-8fe6-ff1d76be8ec0",
"TenantId": "ea80952e-xxxx-xxxx-xxxx-5457852b0f7e",
},
I tried to define the redirect url in Azure App registration blade, but the defined values is not picking from the app.
Azure App registration redirect url
Can someone help me to resolve this issue.
Attached screenshot for your reference.
Screenshot of error response after successful authentication
To deal with this kind of problem, you can try a general solution:
When you visit the application url , you will be redirected to the login page. Decode the authorization request url, you will find redirect_url, copy the value of redirect_url and paste it into the azure portal, and try again.

How to secure an Azure Function accessed by a Blazor Wasm app with Azure AD B2C?

Scenario: I have a Blazor wasm app secured with B2C Authentication that needs to call an HTTP triggered Azure function. What would be the best method to secure that Azure function so that only the Blazor app and/or authenticated users could call that function?
So far I know how to secure the Blazor app with B2C (obviously silly!) and I've also been able to add B2C auth to an Azure function and secure the calls by validating the jwt token. But it's not clear in my head how the two parts should jive together.
Should I expose an API in the app registration of the Azure Function in the B2C tenant? If so, how the Blazor app would make authenticated calls to the Azure function?
Or do I simply send the jwt token from the Blazor app through the http request headers of the Azure function call and then validate that token manually inside the function?
I've been reading a lot of different posts on the subject lately but I still can't figure out what's THE best solution to achieve it.
Any help/cues would be appreciated.
Thanks!
ps: I'm not interested in using the Azure API management since it's a little bit on the pricey side for a pretty simple app solution.
If you want to call Azure function projected by Azure AD B2C, please refer to the following steps
Configure Azure AD B2C for Azure function
Create Azure B2C app.
Web App/API : Yes
Allow Implicit Flow : Yes
Set Reply URL in B2C app: https://{function app url}/.auth/login/aad/callback
Set App ID URL in B2C App : https://{tennat}/{prefix}
Note down B2C apps Application ID.
Define API scope. Go to B2C app => Published scopes.
Get your B2C user flows/policy’s metadata URL. Note down this URL.
It can be obtained from Run User Flow page.
It’s format is like https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/v2.0/.well-known/openid-configuration?p={policy}.
Go to your functions => Authentication / Authorization.
Set following
App Service Authentication : On
Action to take when not authenticated : Login with Azure AD
Authentication providers : Azure AAD
Management Mode : Advanced
Client Id : {Application Id from Step 4}
Issuer URL : {URL from step 6}
Allowed Audience: {Application Id URL from Step 3}
Create Client application For more details, please refer to here.
Configure CORS policy in Azure Function
Configure Application
Create
dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" --client-id "{CLIENT ID}" --domain "{TENANT DOMAIN}" -o {APP NAME} -ssp "{SIGN UP OR SIGN IN POLICY}"
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");
}
}

Blazor standalone client calling a function via Azure B2C

Is there a good example or a walkthrough of a Blazor standalone app calling a function app via an Azure Active Directory B2C passing in a claim with an identity to the function?
I have been working my way through the documentation,
Secure an ASP.NET Core Blazor WebAssembly standalone app with Azure Active Directory B2C and
ASP.NET Core Blazor WebAssembly additional security scenarios but cannot get past 404 result.
So what am I trying to achieve? I want to put together a couple of POCs. The first is a Blazor standalone client app, authenticating via B2C, then passing an authorisation token claims token to an azure function, where I can unpack the user id and email address. The second is same as above, but with Api Management between the Blazor client and the functions api. Because of the nature of the project I am using the consumption plan for both the functions and api management.
So just concentrating on the first case (Blazor - B2C - Function), on the assumption if I get that to work, the api will follow…
I have a B2C client tenant with 2 applications: a front end app authorised for the scopes of a 2nd B2C application for the api. My Function app has authentication/authorisation set to 'Login with Active Directory' with the client ID set to the Front end app's client id, the issuer uri set to the B2C's pocsignupsignin Userflow and the 'Allowed Token Audiences' set to the client id of the Api in B2C.
I can get a JWT token via a browser and using postman successfully call a function in my function app passing a bearer token.
My Blazor app can log in to B2C. If I have no authorisation configured for the web app, then my function call is successful.
But once I turn authorisation I run into CORS 404 - origin 'https://localhost:44389' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. But I have CORS configured with 'Enable Access-Control-Allow-Credentials' and my client url configured.
What am I missing?
I also suspect that the token with the id will not be passed correctly.
From Program.cs
builder.Services.AddHttpClient("ServerAPI",
client => client.BaseAddress = new Uri(functionURI))
.AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add(readScopeURI);
options.ProviderOptions.DefaultAccessTokenScopes.Add(writeScopeURI);
Console.WriteLine($"options.ProviderOptions.DefaultAccessTokenScopes {options.ProviderOptions.DefaultAccessTokenScopes}");
});
From CustomAuthorizationMessageHandler
public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
{
public CustomAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { B2CClientUrl },
scopes: new[] { "read", "write" });
}
}
From appsettings
"AzureAdB2C":
{
"Authority": B2C signupsignin uri,
"ClientId": B2C frontend client,
"ValidateAuthority": false
}
Function call
async Task GetFromDedicatedFunctionClient(string subUrl)
{
try
{
var client = ClientFactory.CreateClient("ServerAPI");
Console.WriteLine($"client.BaseAddress {client.BaseAddress}");
result =
await client.GetStringAsync(subUrl);
}
catch …
}

Resources