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

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.

Related

Azure B2C Works On My Local Machine But Not On Azure

I have created a Blazor application that calls a Web API(.Net) and uses Azure AD B2C for authentication. This works fine on my local machine. I can authenticate via the login screen and call the relevant endpoint. Once I deploy the application to Azure I get this error on the browser:
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user
Failed to load resource: the server responded with a status of 401 (Unauthorized)
On the Blazor(UI) side I have this set up:
"AzureAd": {
"Authority": "https://CarehomeRoomBookingTest.b2clogin.com/CarehomeRoomBookingTest.onmicrosoft.com/B2C_1_SignUpIn",
"ClientId": "77##############################",
"ClientSecret": "99#########################",
"ValidateAuthority": false
}
On the Web API side I have this set up:
"AzureAdB2C": {
"Instance": "https://CarehomeRoomBookingTest.b2clogin.com",
"ClientId": "16#############################",
"Domain": "CarehomeRoomBookingTest.onmicrosoft.com",
"SignedOutCallbackPath": "/signout/B2C_1_susi_reset_v2",
"SignUpSignInPolicyId": "B2C_1_SignUpIn",
"TenantId": "38#############################"
}
Why would this be happening when the application is deployed and hosted on Azure?
Please check if any of below is your case:
1.See if scope for your API that Your front-end app needs to use is correct. This way it will get an access token which is meant for your API. Register a
scope for your API app registration through the Expose an API
section and use the scope in your front-end app.
and grant admin consent :
Your scopes will be present this way
Please make sure to include the scopes exposed in the portal for your backend api in the auth in your code
Also please check if you have given proper permissons or if use of
delegated permissions is the issue .See
getting-401-unauthorized-error-StackOverflow

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

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

How to get Azure OIDC to respect my redirect URI?

I have an app hosted on Azure PaaS using Open ID Connect for auth.
The app URL is like: https://env.app.entity.my.domain
The Azure ASE is: https://entity-app-env-web.webenvase.my.domain
As long as I configure a redirect URI for https://entity-app-env-web.webenvase.my.domain/signin-oidc in Azure, it works. That's because it's ignoring the redirect URI in my settings. But that's not what I want. I will obviously want to return the user to the app's URL.
No matter what values I put for my RedirectUri or CallbackPath, it defaults to the ASE URL. How can I fix that?
appsettings.json:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Issuer": "https://sts.windows.net/<tenant id>/",
"Domain": "my.azure.domain",
"TenantId": "<tenant id>",
"ClientId": "<client id>",
"RedirectUri": "https://env.app.entity.my.domain/signin-oidc"
}
Startup.cs (auth config):
services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireRole(Role.Administrator)
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddMicrosoftIdentityUI();
I found from this answer and elsewhere that the redirect uri is automatically calculated not using the value from the configs. The one in the configs will be used in some cases but not for the auth call to Azure.
After monkeying around with it for some time our server team started removing rules on the f5 and we found that the header rewrite rule that is typical for our other apps was the issue. Specifically, it was causing the auth cookie to be rejected and stripped at the browser during redirection.
We removed the rule and all is well again.

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 …
}

How to programmatically redirect to Azure AD sign-in and sign-out pages in ASP.NET Core MVC?

My ASP.NET Core 2.2 MVC app is using Azure AD to authenticate users. In startup.cs I added Azure AD:
services
.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.Authority = options.Authority + "/v2.0/";
options.TokenValidationParameters.NameClaimType = "preferred_username";
});
Authorization is done by a policy check:
services.AddAuthorization(options =>
{
options.AddPolicy("AdministratorOnly", policy => {
policy.RequireClaim("groups", adminGroupId);
});
});
In appsettings.json I have all the required configuration:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "662f1be2-...",
"ClientId": "30eb6c27-...",
"CallbackPath": "/signin-oidc",
"SignedOutCallbackPath ": "/signout-callback-oidc"
}
If I try to access a controller decorated with [Authorize(Policy = "AdministratorOnly")] it will redirect to Azure AD and handle the login process and eventually redirect back to my app.
Questions:
Is there a prescribed to kick off the login process (preferably in a popup window)? Where do I get the URL from to redirect to?
How can I provide a button to let users logout again? If I redirect to "/signout-oidc" I'm getting signed out but I end up on a blank page.
Documentation explains it all. It is backed by a solid source code repository.
In general, the AzureAD middleware is taking care about redirection to Azure AD when the user is not authenticated. This is checked every time user ends up on action decorated with [Authorize] attribute.
As for Logout - if you use the oidc-logout, check out the sample and explanations here.

Resources