Hi @Spohn, Albert F. (Al) ,
Give this a try, maybe it'll help you.
In the .NET Core web API:
- In the appsettings.json file add a section like this one: "Authentication": {
"Instance": "Instance here",
"TenantId": "TenantIdHere",
"ClientId": "ClientIdHere",
"ClientSecret": "ClienSecretHere"
} - Create a class for the authentication options named AuthenticationOptions
public class AuthenticationOptions { public string ClientId { get; set; } public string ClientSecret { get; set; } public string Instance { get; set; } public string TenantId { get; set; } }
- In the Startup.cs class, map your configuration to your AuthenticationOptionsClass:
services.Configure<AuthenticationOptions>(Configuration.GetSection("Authentication"));
- In the ConfigureServices of the Startup.cs class, add the following:
serviceCollection.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddAzureAdBearer();
‼ AddAzureAdBearer()
is a custom extension method of AuthenticationBuilder (which is imported from Microsoft.AspNetCore.Authentication
).
Here's what it looks like:
public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder)
{
builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureJwtBearerOptions>();
builder.AddJwtBearer();
return builder;
}
JwtBearerOptions
is imported from this dependency Microsoft.AspNetCore.Authentication.JwtBearer
Next, create the class ConfigureJwtBearerOptions
:
public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
{
private readonly AuthenticationOptions _azureOptions;
public ConfigureJwtBearerOptions(IOptions<AuthenticationOptions> authenticationOptions)
{
_azureOptions = authenticationOptions.Value;
}
public void Configure(string name, JwtBearerOptions options)
{
options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
}
public void Configure(JwtBearerOptions options)
{
Configure(string.Empty, options);
}
}
5. In the Configure method of the Startup class, add the following:
app.UseAuthentication();
6. Add the Authorize attribute on your controller
Here we are using a JwtBearer for the authentication. All you have to do next is to get this bearer using MSAL, put it in the header of your request, and call the API. You can find a very good example of a JS application doing that here :
https://github.com/Azure-Samples/ms-identity-b2c-javascript-spa .
You should replace the values with yours in the authConfig.js file, apiConfig.js and policies.js files.