How to redirect on backend for Angular application using Itfoxtec to access app through Azure Active Directory - itfoxtec-identity-saml2

I am new to using ITfoxtec for Azure Active Directory SAML logins. I read the StackOverflow entry for Nuget ITfoxtec SAML & Angular (and other similar entries for CORS issues), but I still do not understand how to adapt the GitHub Angular example from https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2 to my needs. When running the ITfoxtec GitHub example, the Login method of the AuthController.cs file is immediately executed when I launch the test Angular application, and brings up the Azure Active Directory login prompt.
For my application, I need to click a "Login using Azure Active Directory" button on the Angular front end to call a backend method that can then redirect to another method to attempt login.
.NetCore C# code:
SSOController.cs file:
// This method is called by an Angular front end button when the user wishes to log in via Azure Active Directory SSO
[AllowAnonymous]
[Route("AzureAuth")]
[HttpGet]
public IActionResult AzureAuth(string returnUrl = null)
{
var binding = new Saml2RedirectBinding();
Saml2Configuration config = GetSamlConfig();
binding.SetRelayStateQuery(new Dictionary<string, string> { { relayStateReturnUrl, returnUrl ?? Url.Content("https://localhost:44397/api/sso/AssertionConsumerService") } });
//return binding.Bind(new Saml2AuthnRequest(config)).ToActionResult();
// This gives a CORS error, so we have do ensure that we do the redirection at the backend
// so we try redirecting with "RedirectToAction"
return RedirectToAction("https://localhost:44397/api/sso/AssertionConsumerService");
}
My AssertionConsumerService() method (located in Dev at "https://localhost:44397/api/sso/AssertionConsumerService"), which I need to be redirected to:
[Route("AssertionConsumerService")]
[HttpPost]
public async Task<IActionResult> AssertionConsumerService(HttpRequestMessage request)
{
// After user enters AAD SSO information, redirect should point to here.
// This API endpoint is hit if I test from Azure Enterprise Application SSO testing with the redirect API set to this method.
// I do not understand how to do backend redirects from AzureAuth() method to this method, and ensure that the HTTP request data is correct.
}

Just a follow up to my own question. For logging in directly from the Angular front end, I am having success with using "#azure/msal-angular". Once the end user clicks the "Log in with Azure Active Directory" button and is authenticated back to the frontend, I forward the authentication details to the backend for authorization checks.
I am still using ITfoxtec at the backend to process what can be directly sent from the "Azure Enterprise Applications > Set up single sign on > Test single sign-on with ..." for testing purposes. With the Azure "App registrations > Authentication > Platform Configuration" set to "Single-Page Application", I am making good progress in development and testing.

Sounds like you got a solution.
You can load the Angular application before login if it is hosted a place in the ASP.NET application that do not require the user to be authenticated. Then you can start the login process your selv and validate if the user is authenticated.

Related

Blazor WASM with Azure AD SSO

I have a Blazor WASM client and a Web API with working Azure AD authentication and authorization but the users always have to push the button to log in. I want to use SSO for make them easy this process. I tried to find on Internet how I can put this feature in the application but no success. Can someone to show the right direction, please?
I do not insert source code because those who are experienced in this will know what it is about. Thx
• Yes, you can configure SSO in Blazor WASM app very easily by following the below said procedure as shown. Also, you need to determine the authentication method for the Blazor WASM app, i.e., SAML, OAuth 2.0, OpenID as such. Therefore, I am considering SAML as the authentication mechanism in here.
To facilitate the SAML SSO authentication through Azure AD, you will have to install packages related to it in your .NET Core product from its official website. Here, we are using ‘ComponentSpace.SAML.2.0’ package using the NuGet Manager. Once the installation is complete, we need to inject the service of ‘ComponentSpace’ in our project by adding service and cookies in the ‘Program.cs’ file whose code looks like this: -
builder.Services.Configure<CookiePolicyOptions>(options =>
{
// SameSiteMode.None is required to support SAML SSO.
options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.ConfigureApplicationCookie(options =>
{
// Use a unique identity cookie name rather than sharing the cookie across applications in the domain.
options.Cookie.Name = “StudentPortal.Identity”;
// SameSiteMode.None is required to support SAML logout.
options.Cookie.SameSite = SameSiteMode.None;
});
// Add SAML SSO services.
builder.Services.AddSaml(builder.Configuration.GetSection(“SAML”));
Once done, we can modify the ‘appsettings.json’ file to add to the ‘ComponentSpace’ settings. There are many parts which we can add in the ‘appsettings.json’ file,i.e., ‘schema’, ‘LocalServiceProviderConfiguration’, ‘PartnerIdentityProviderConfigurations’, ‘SingleSignOnServiceUrl’, ‘SingleLogoutServiceUrl’ and ‘ArtifactResolutionServiceUrl’ refers to the IDP server side’s service URL wherein it should be your Azure Cloud’s URL and these URLs are where our applications send sign-on and logout requests which also includes the ‘PartnerName’, i.e., IDP’s name and URL.
To do so, you will have to include the below in your ‘appsettings.json’ file placed under ‘wwwroot’ folder: -
{
"oidc": {
"Authority": "< insert the SSO provider URL here >",
"ClientId": "< unique client id as specified in the SSO provider >",
"ResponseType": "code",
"DefaultScopes": [
"openid",
"profile"
],
"PostLogoutRedirectUri": "authentication/logout-callback",
"RedirectUri": "authentication/login-callback"
}
}
Thus, once done, we will add a new file to the same folder by the name of ‘LoginDisplay.razor’ which is displayed as follows: -
#using Microsoft.AspNetCore.Components.Authorization
#using Microsoft.AspNetCore.Components.WebAssembly.Authentication
#inject NavigationManager Navigation
#inject SignOutSessionStateManager SignOutManager
<AuthorizeView>
<Authorized>
<button class="nav-link btn btn-link" #onclick="BeginSignOut">Log out</button>
</Authorized>
<NotAuthorized>
Register
Log in
</NotAuthorized>
</AuthorizeView>
#code{
private async Task BeginSignOut(MouseEventArgs args)
{
await SignOutManager.SetSignOutState();
Navigation.NavigateTo("authentication/logout");
}
}
Thus, as all the configurations required are done as given above, the program will call ‘SAML/InitiateSingleSignOn’ function and send an SSO sign-in request to IDP, and now our program automatically run into the ‘SAML/AssertionConsumerService’ function and start to wait for IDP's reply, after receiving the response from the IDP. Please find the below snapshots for your reference while following the above steps: -
Certificate import: -
Adding ‘SAML Service Provider’ as a SAMLController as said: -
Adding ‘ComponentSpace.SAML.2.0’ package as below: -
For more detailed information, kindly refer to the below links: -
https://kevinzheng1989.medium.com/build-the-azure-sso-login-page-in-blazor-server-application-with-saml-b0959a50c0a6
https://scientificprogrammer.net/2022/08/12/single-sign-on-user-authentication-on-blazor-webassembly-signalr-client/

Replace basic authentication with Azure AD authentication in Web API

I have a Web API that used basic authorization to access the Web API from front end. So we used to pass Authorization header from Frontend Application that contains user login and password in encrypted form and sent to WEB API, where we read authorization header and fetch user login details(UserName, Password) and validate user credentials from Active directory.
Now we are implementing Azure AD integration and we are not able to send user password in Authorization header. So API fails to validate user credentials and it break the flow. Also I am getting httpcontext.current.user as null.see below code
public class UserdataController : ApiController
{
private readonly KMMContext db = new KMMContext(HttpContext.Current?.User?.Identity?.Name ?? "");
You'll need to use MSAL.
A good starting point is here https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview
Some examples can also be found here. This one is for a javascript/nodejs client since it was not mentioned which frontend framework was used.
https://github.com/Azure-Samples/active-directory-javascript-nodejs-webapi-v2
Basically your WebAPI will now be receiving a JWT token instead of the user credentials.

EasyAuth with a SPA and AzureFunction on different hosts

I'm trying to use EasyAuth (aad) with a SPA, which is on "localhost:8080" at the moment, and an Azure Function which is hosted in Azure ({function-app}.azurewebsites.net. The intent is for the SPA to call a secured endpoint on the Azure Function. So, I have the Azure Function Registered as an application in AD, and the authentication redirect in the SPA to the Azure Function EasyAuth endpoint appears to be working, but the redirect back to the localhost SPA via the post_login_redirect_url is not.
I added http://localhost:8080 to the AAD registered application as an allowed redirect URI. However, if I fully qualify the URL I am redirected back to {function-host}/.auth/login/done. Is there an expectation that the SPA runs under the same hostname as the azure function, or is there a way to configure the setup to allow any URL for the SPA host?
Behavior
In terms of HTTP data during behavior, once login succeeds .auth/login/aad/callback is loaded with the following prior to redirecting to the default done page and stopping.
Response Header
Location = {function-host}/.auth/login/done
Form Data:
state = http://localhost:8080
code = auth code
id_token = auth token
How I called it from the SPA
function processAuthCheck(xmlhttp) {
if (xmlhttp.status == 401) {
url = "https://{function-app}.azurewebsites.net/.auth/login/aad?"
+ "post_login_redirect_url=" + encodeURI("http://localhost:8080");
window.location = url;
} else if (xmlhttp.status != 200) {
alert("There is an error with this service!");
return;
}
var result = JSON.parse(xmlhttp.responseText);
console.log(JSON.stringify(result));
return;
};
Regarding the issue, please refer to the following steps
Register Azure AD application to protect azure function with easy auth
Register client-side application
a. Register single-page application
b. In the Implicit grant and hybrid flows section, select ID tokens and Access tokens.
c. Configure API permissions
Enable CORS in Azure function
Code
a. Integrate Azure AD auth in your spa application with Implicit grant flow. After doing that, when users access your application, they need to enter their AD account to get access token
b. Client exchanges this accessToken for an 'App Service Token'. It does this by making a POST to https://{app}.azurewebsites.net/.auth/login/aad with the content { "access_token" : "{token from Azure AD}" }. This will return back an authenticationToken
c. Use that authenticationToken in a header named x-zumo-auth. Make all requests to your function app using that header.
For more details, please refer to here and here. Regarding how to implement Azure AD in spa, please refer to here.

Blazor WASM calling Azure AAD secured Functions API

I have an Azure Functions API which uses Azure Active Directory authentication. I can test locally and deployed using a browser and curl calls in a process of:
Get a code
Use the code to get a token
Pass the token to authenticate and get the function result.
I now want to call this API from my Blazor WASM app but I'm sure there must be a nice MSAL call to do all the authentication but I cannot find any documentation on what that might be.
Does anyone have a code snippet to illustrate what needs to happen?
Further Information
My Azure Functions App and Blazor WASM client are not part of the same project and are hosted on different sub-domains of Azure hypotheticalapi.azurewebsites.net and hypotheticalweb.azurewebsites.net.
The web client application registration has API Permissions for the API and the API has an application registration which exposes itself with the scope that the client app has permissions for.
Again, the API and Web app work individually. I just don't seem able to get them to talk.
I have been following the "ASP.NET Core Blazor WebAssembly additional security scenarios" documentation but after several attempts I keep coming back to the error:
Microsoft.JSInterop.JSException: invalid_grant: AADSTS65001:
The user or administrator has not consented to use the application with ID 'e40aabb0-8ed5-4833-b50d-ec7ca4e07996' named 'BallerinaBlazor5Wasm'.
Send an interactive authorization request for this user and resource.
Even though I have revoked/deleted the client's permissions on the API, it has never repeated asking for consent. Is there a way I should clear the consent I previously gave? No idea how I might do that.
This GitHub Issue appears to be relevant.
I was stuck for the last two weeks with the same error code in the same setting: Blazor WASM talking to an AAD secured Azure Functions app.
What appeared to be a problem in my case was the scopes that I was listing in the http request when contacting AAD identification provider endpoints. Almost all examples I came across use Microsoft Graph API. There, User.Read is the scope that is given as an example. My first though was that even when I am contacting my own API I have to include the User.Read scope in the request because I was reasoning that this scope is necessary to identify the user. However, this is not the case and the only scope that you have to list when you call the authorize and token endpoints is the one that you exposed under the "Expose an API blade" in your AAD app registration.
I am using the OAuth2 authorization code in my example and not the implicit grant. Make sure that in the manifest of your API registration you have set "accessTokenAcceptedVersion": 2 and not "accessTokenAcceptedVersion": null. The latter implies the use of implicit flow as far as I know.
The scope the I exposed in my API is Api.Read. You can expose more scopes if you need but the point is that you only ask for scopes that you exposed.
I also have both following options unticked (i.e. no implicit flow). However, I tried with selecting "ID token" and it still worked. Note that the "ID token" option is selected by default if you let the Azure Portal create your AAD app registration from your function app Authentication blade.
Blazor code
Program.cs
This code has to be added.
builder.Services.AddScoped<GraphAPIAuthorizationMessageHandler>();
builder.Services.AddHttpClient("{NAME}",
client => client.BaseAddress = new Uri("https://your-azure-functions-url.net"))
.AddHttpMessageHandler<GraphAPIAuthorizationMessageHandler>();
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
.CreateClient("{NAME}"));
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
// NOTE: no "api://" when providing the scope
options.ProviderOptions.DefaultAccessTokenScopes.Add("{you API application id}/{api exposed scope}");
});
appsetting.json
"AzureAd": {
"Authority": "https://login.microsoftonline.com/{aad tenant id}",
"ClientId": "{application id of your blazor wasm app}",
"ValidateAuthority": true
}
GraphAPIAuthorizationMessageHandler.cs
Note that this class can have a different name. you'll then also reference a different name in Program.cs.
public class GraphAPIAuthorizationMessageHandler : AuthorizationMessageHandler
{
public GraphAPIAuthorizationMessageHandler(IAccessTokenProvider provider,
NavigationManager navigationManager)
: base(provider, navigationManager)
{
ConfigureHandler(
authorizedUrls: new[] { "https://your-azure-functions-url.net" },
// NOTE: here with "api://"
scopes: new[] { "api://{you API application id}/{api exposed scope}" });
}
}
I hope this works. If not, let me know.
At least you need to get the access token, then use the token to call the function api. In this case, if you want to get the token in only one step, you could use the client credential flow, MSAL sample here, follow every part on the left to complete the prerequisites.
The following are the approximate steps(for more details, you still need to follow the sample above):
1.Create a new App registration and add a client secret.
2.Instantiate the confidential client application with a client secret
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
3.Get the token
string[] scopes = new string[] { "<AppId URI of your function related AD App>/.default" };
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
4.Call the function API
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
// Call the web API.
HttpResponseMessage response = await _httpClient.GetAsync(apiUri);
...
}

Owin OpenIdConnect Active Directory HttpContext.GetOwinContext doesn't open microsoftonlin login page

I'm trying to use Owin and OpenIdConnect to authenticate users via active directory (office 365 online). I've followed this example and I managed to create a new MVC test project and get it all working. (Settings for AD app id, tenant, Web config etc all fine).
I'm now trying to add that functionality into my existing ASP.net mvc application and I can't get the dang thing to work.
This is what I have: An Account Controller with a "void" action like this (from the example that works in my PoC but not in my actual application):
public void SignIn()
{
// Send an OpenID Connect sign-in request.
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
When this action is invoked, I expect the browser to be directed to: login.microsoftonline.com..., but instead it opens this page: https://localhost:44301/Account/Login?ReturnUrl=%2fAccount%2fSignIn
It's like it's calling some sort of redirect somewhere and I can't see where.
Help!
I found the answer. I had to do 2 things:
Remove the WebMatrix dll's from the references (apparently nuget package for mvc put it there, so it might come back)
Remove authentication mode="Forms" from web.config
Thanks.

Resources