Previously our web application (NET Framework 4.8) was using Windows Authentication, then we switched to Sustainsys/Saml2 with Startup.cs and OWIN to login.
It turns out that SAML login cannot be used by Task Scheduler/CRON and by external API consumers, because SAML requires human interaction. So SAML must be disable and other Authentication must be used for the following pages:
background scripts (aspx pages) run by Task Scheduler;
3rd party application use some of our APIs GET/POST;
Task Scheduler do not support saml2 and so and external 3rd party apps, they connect via stored in their config login/password.
As far i know SAML2 requires human interaction via web popup (azure in our case) and cannot be automated.
Issue was solved by using OAuth (token) along with SAML. If OAuth is put before SAML in OWIN Startup.cs, token API will work even is SAML is activated (i think SAML code see that Thread.CurrentPrincipal is already set, so SAML step is skipped)
using System;
using System.Web.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Owin;
using Owin;
using BundleTable = System.Web.Optimization.BundleTable;
////
[assembly: OwinStartup(typeof(MyApplication.App_Start.Startup))]
namespace MyApplication.App_Start
{
public class Startup
{
// Configure the HTTP request pipeline.
public void Configuration(IAppBuilder app)
{
ServiceCollection services = new ServiceCollection();
ConfigureServices(services);
OAuthConfiguration oauthConfig =
MyConfigurationManager.ReadOAuth();
OAuthSetup oauth = new OAuthSetup(app, oauthConfig);
/* server + consumer
IdentityServer 3
// server. Probably this step can be skipped if use Azure as server
app.Map(configuration.AuthServerUrl, idsrvApp =>
{
idsrvApp.UseIdentityServer(options);
});
//consumer
app.UseJwtBearerAuthentication,
app.UseClaimsTransformation */
oauth.Use();
SamlConfiguration samlConfig =
MyConfigurationManager.ReadSaml();
SamlSetupSustainsys saml = new SamlSetupSustainsys(app, samlConfig);
/*
Sustainsys
app.UseSaml2Authentication(options);*/
saml.Use();
WebApiConfig.Register(config);
app.RequireAspNetSession();
app.UseWebApi(config);
BundleTable.EnableOptimizations = false;
BundlingConfig.Register(BundleTable.Bundles);
}
// Add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddMvcCore();
}
}
}
Related
Are there any examples of using itfoxtec-identity-saml2 with asp.net core Identity.
Specifically, I have many SAML Idps (https://stubidp.sustainsys.com, Okta, Auth0, Salesforce, etc) and I want to add them using AuthenticationBuilder.
public static class Saml2Extensions
{
public static AuthenticationBuilder AddSaml(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<Saml2Options> configureOptions)
{
...
}
}
A good example would have a mix in of Google, Azure both using OIDC, and a few SAML ones.
I'm afraid that I do not have sutch an example. I always put a proxy / broker IdP in between, in my case I use FoxIDs. That way the application only need to know about one IdP and would then ask the broker IdP to handle the up-stream IdP authentication.
With NET 5 officially released, this evening I've migrated from Net Core 3.1 to NET 5, all seemed to go smoothly until I tried to run the app and now find a couple of squiggly lines under two items in the startup.cs that are associated with Microsoft Identity Web platform. This is obviously an instant fail! I wont be able to fire up the app or login to Azure AD until I have this fixed.
After modifying the csproj file to NET5, I then went to nuget manager and updated all the packages.
I've absolutely no idea where to start on this issue :(
Screenshot of the startup.cs file with the squiggles:
csproj file:
Nuget Manager with updated packages:
I notice that the package references at the top of the startup.cs file for MS Identity Web are now greyed out since the migration:
Code from the startup.cs file:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public TokenValidatedContext Context { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Added to original .net core template.
// ASP.NET Core apps access the HttpContext through the IHttpContextAccessor interface and
// its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor
// when you need access to the HttpContext inside a service.
// Example usage - we're using this to retrieve the details of the currrently logged in user in page model actions.
services.AddHttpContextAccessor();
// DO NOT DELETE (for now...)
// This 'Microsoft.AspNetCore.Authentication.AzureAD.UI' library was originally used for Azure Ad authentication
// before we implemented the newer Microsoft.Identity.Web and Microsoft.Identity.Web.UI NuGet packages.
// Note after implememting the newer library for authetication, we had to modify the _LoginPartial.cshtml file.
//services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
// .AddAzureAD(options => Configuration.Bind("AzureAd", options));
///////////////////////////////////
// Add services required for using options.
// e.g used for calling Graph Api from WebOptions class, from config file.
services.AddOptions();
// Sign-in users with the Microsoft identity platform
services.AddSignIn(Configuration);
// Token acquisition service based on MSAL.NET
// and chosen token cache implementation
services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { GraphScopes.UserRead })
.AddInMemoryTokenCaches();
// Add the MS Graph SDK Client as a service for Dependancy Injection.
services.AddGraphService(Configuration);
// Create a new instance of the class that stores the methods called
// by OpenIdConnectEvents(); i.e. when a user logs in or out the app.
// See section below :- 'services.Configure'
OpenIdEvents openIdEvents = new OpenIdEvents();
// The following lines code instruct the asp.net core middleware to use the data in the "roles" claim in the Authorize attribute and User.IsInrole()
// See https://learn.microsoft.com/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 for more info.
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
// The claim in the Jwt token where App roles are available.
options.TokenValidationParameters.RoleClaimType = "roles";
// Advanced config - capturing user events. See OpenIdEvents class.
options.Events ??= new OpenIdConnectEvents();
options.Events.OnTokenValidated += openIdEvents.OnTokenValidatedFunc;
// This is event is fired when the user is redirected to the MS Signout Page (before they've physically signed out)
options.Events.OnRedirectToIdentityProviderForSignOut += openIdEvents.OnRedirectToIdentityProviderForSignOutFunc;
// DO NOT DELETE - May use in the future.
// OnSignedOutCallbackRedirect doesn't produce any user claims to read from for the user after they have signed out.
options.Events.OnSignedOutCallbackRedirect += openIdEvents.OnSignedOutCallbackRedirectFunc;
});
// Adding authorization policies that enforce authorization using Azure AD roles. Polices defined in seperate classes.
services.AddAuthorization(options =>
{
// This line may not work for razor at all, havent tried it but what was used in MVC from the MS Project example. Dont delete just yet...
//options.AddPolicy(AuthorizationPolicies.AssignmentToUserReaderRoleRequired, policy => policy.RequireRole(AppRole.UserReaders));
// NOTE BELOW - I had to change the syntax from RequireRole to RequireClaim
options.AddPolicy(AuthorizationPolicies.AssignmentToEditRolesRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.EditRoles));
options.AddPolicy(AuthorizationPolicies.AssignmentToViewLogsRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.ViewLogs));
options.AddPolicy(AuthorizationPolicies.AssignmentToViewUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.ViewUsers));
options.AddPolicy(AuthorizationPolicies.AssignmentToCreateUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.CreateUsers));
options.AddPolicy(AuthorizationPolicies.AssignmentToEditUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.EditUsers));
options.AddPolicy(AuthorizationPolicies.AssignmentToDeleteUsersRoleRequired, policy => policy.RequireClaim(ClaimTypes.Role, AppRole.DeleteUsers));
});
services.AddRazorPages().AddMvcOptions(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
// Add the HttpClient factory into our dependancy injection system.
// That way we can access it at any point.
// Used for consuming REST Api throughout the Webb App.
services.AddHttpClient();
// Adds the service for creating the Jwt Token used for calling microservices.
// Note we are using our independant bearer token issuer service here, NOT Azure AD
services.AddScoped<JwtService>();
// Add service for HttpContext Current User Repository.
// Used fir fetching properties of the currently logged in user for logging.
services.AddScoped<ICurrentUser, CurrentUser>();
// The AddAntiforgery() method configures anti-forgery service to pick the anti-forgery
// token from request headers rather than request body. This is required because we will
// be issuing Ajax requests to the razor page and there won't be any full page post-backs.
services.AddAntiforgery(options => options.HeaderName = "MY-XSRF-TOKEN");
}
I just don't know how to troubleshoot this...
OK, got it working. The first issue I got the answer from another post:
The services.AddSignIn() is available in the nuget package of Microsoft.Identity.Web up to version 0.1.5 Preview version, the above versions don't contain the services.AddSignIn()
In my case I'm using Microsoft.Identity.Web ver 1.3.0
I replaced the code shown directly below with the code section at the bottom:
Old Code:
// Sign-in users with the Microsoft identity platform
services.AddSignIn(Configuration);
// Token acquisition service based on MSAL.NET
// and chosen token cache implementation
services.AddWebAppCallsProtectedWebApi(Configuration, new string[] { GraphScopes.UserRead })
.AddInMemoryTokenCaches();
Replaced the above with the following code:
// Sign-in users with the Microsoft identity platform
//services.AddSignIn(Configuration);
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
// Token acquisition service based on MSAL.NET and chosen token cache implementation
.EnableTokenAcquisitionToCallDownstreamApi(new string[] { GraphScopes.UserRead })
.AddInMemoryTokenCaches();
I've run some quick checks to ensure that I'm able to perform changes to a user profile which is using the MS Graph so I'm comfortable enough this solved my issue.
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");
}
}
I have a scenario where I have a Blazor WASM (client only) app that is secured via AD B2C. As per the documentation I have read, I have registered an application in AD B2C (e.g. BlazorApp) and wired the Blazor app to this instance. This Blazor app makes API calls to a .NET Core Web API where the endpoints are secured (using the [Authorize] attributes). As per the documentation I have read, I have also registered the Web API in AD B2C (e.g. WebApi) and wired the API to connect to this instance.
The problem I have is that when I authenticate in the Blazor app, and then pass the access/id token through the API calls, the Web API can't authenticate that token (unauthorized error response). It works when I wire the Web API to connect to the BlazorApp registration (I'm guessing because that is where the token was issued from). But this seems to go against the recommendation of registering each app/api in AD as a separate registration.
How can I get the WebApi registration to recognise a token issued by BlazorApp? Am I going about this wrong and should I just wire the Web API to talk to the BlazorApp instance?
Additional Information:
Blazor WASM (client) - Program.cs
(sensitive information removed)
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
...
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add(#"https://<tenant name>.onmicrosoft.com/blazorapp/app.read");
options.ProviderOptions.DefaultAccessTokenScopes.Add(#"https://<tenant name>.onmicrosoft.com/blazorapp/app.write");
});
...
await builder.Build().RunAsync();
}
Blazor WASM (client) - appsettings.json
(sensitive information removed)
{
"AzureAdB2C": {
"Authority": "https://<tenant name>.b2clogin.com/<tenant name>.onmicrosoft.com/B2C_1_SignUpSignIn",
"ClientId": "<BlazorApp Application ID>",
"ValidateAuthority": false
}
}
Web API (.NET Core 3.1) - StartUp.cs
(sensitive information removed)
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
.AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
services.AddControllers();
...
}
Web API (.NET Core 3.1) - appsettings.json
(sensitive information removed)
NOTE: Authentication works when I replace the WebApi Application ID with the BlazorApp Application ID
{
"AzureAdB2C": {
"Instance": "https://<tenant name>.b2clogin.com/tfp/",
"ClientId": "<WebAPI Application ID>",
"Domain": "<tenant name>.onmicrosoft.com",
"SignUpSignInPolicyId": "B2C_1_SignUpSignIn"
},
...
}
Your project is not using OBO flow, OBO flow requires three applications, specifically one client-side and two api-side, see here.
Back to the problem, first of all your problem is misconfigured scope, as the api-side app needs to expose its own api, the API permission on your blazor app side gets access to the api-side, so the access to the scope is configured on the api-side, so we need to put https://<tenant name>.onmicrosoft.com/webapiapp/app.read on the scope, your blazor app is only used to configure access.
It works because you use blazor app to request the blazor app's own api, which is feasible, although a little strange, to request yourself.
So for your project, the correct request should be like this.
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
...
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add(#"https://<tenant name>.onmicrosoft.com/webapiapp/app.read");
options.ProviderOptions.DefaultAccessTokenScopes.Add(#"https://<tenant name>.onmicrosoft.com/webapiapp/app.write");
});
...
await builder.Build().RunAsync();
}
{
"AzureAdB2C": {
"Instance": "https://<tenant name>.b2clogin.com/tfp/",
"ClientId": "<Application ID>",
"Domain": "<tenant name>.onmicrosoft.com",
"SignUpSignInPolicyId": "B2C_1_SignUpSignIn"
},
...
}
I'm running some tests with MSAL but unfortunately it's not working as expected.
I had all configured for an ASP.NET MVC (.net 4.6) + Angular 1.6 SPA application with ADAL and ADAL Angular. All worked just fine but then I decided to try MSAL.
My configured provider's OnValidateIdentity handler in Startup.Auth.cs was being hit correctly with ADAL and I could add additional claims:
Provider = new OAuthBearerAuthenticationProvider
{
OnValidateIdentity = async context =>
{
Now that I changed to MSAL for Angular JS, I'm getting the ID Token and the Access Token but my OnValidateIdentity handler is not being hit anymore.
Is using app.UseWindowsAzureActiveDirectoryBearerAuthentication still valid when using MSAL?
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
.
.
.
MSAL is meant to be used with converged/v2.0 application registrations, while ADAL is usually meant to be used with v1.0 App registrations,
You should create a new application using the new portal in portal.azure.com if you're trying to migrate to the v2 endpoint. In addition to that these docs go over creating a v2.0 App Registration : https://learn.microsoft.com/en-us/graph/auth-register-app-v2
Please refer to this resource for more information on migrating from v1 to the v2 endpoint. https://azure.microsoft.com/en-gb/resources/samples/active-directory-dotnet-v1-to-v2/
In regards to the specifics of using app.UseWindowsAzureActiveDirectoryBearerAuthentication
// NOTE: The usual
WindowsAzureActiveDirectoryBearerAuthenticaitonMiddleware uses a
// metadata endpoint which is not supported by the v2.0 endpoint. Instead, this
// OpenIdConenctCachingSecurityTokenProvider can be used to fetch & use the OpenIdConnect
// metadata document.
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenFormat = new JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")),
});
This is referenced from the startup.cs : https://github.com/AzureADQuickStarts/AppModelv2-NativeClient-DotNet/blob/a69a4cb41e821f0ea8dddc937ea401a03e2f49fe/TodoListService/App_Start/Startup.Auth.cs
Some more good reading that does a bit of a comparison between the v1/v2 sample apps can be found here : https://simonlamb.codes/2017/02/27/net332-introduction-to-authentication-on-azure-active-directory/