I am using AspNetBoilerplate template (.NET CORE 3.1). I am trying to add Azure b2c AD authentication
following official help: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/1-WebApp-OIDC/1-5-B2C
I have successfully implemented above without aspnetBoilerplate template, it works fine. when I try to add this in aspnetboilerplate, it gives me below error on click of Login button.
My View:
<form method="get" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">
<button type="submit" class="btn btn-primary">Login with Microsoft Azure</button>
</form>
Account controller is defined in the Microsoft.Identity.Web.UI NuGet package, in the Area MicrosoftIdentity.
After associating or adding to the asp.net core 3.1 boiler template , check if the namespaces are missed or assembly in dll file is missing and try to add them and by installing the nuget package .
Or
Check if the configurations associated with the project are missing by chance and see if namespace can be configured manually.
According to signs in/out users - Microsoft identity platform | Microsoft Docs
In ASP.NET, selecting the Sign-in button in the web app triggers the
SignIn action on the AccountController controller. In previous
versions of the ASP.NET core templates, the Account controller was
embedded with the web app. That's no longer the case because the
controller is now part of the Microsoft.Identity.Web.UI NuGet package.
See AccountController.cs for details. This controller also handles the
Azure AD B2C applications.
Check with below code in configure services method in startup class
services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C");
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddRazorPages();
services.AddOptions();
services.Configure<OpenIdConnectOptions>(Configuration.GetSection("AzureAdB2C"));
}
And the below in Configure() in Startup.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
Check with the name spaces to be injected in views : azure ad b2c-asp.net core 3.1.
Add the following settings in the appsettings.json
{
"AzureAdB2C": {
"Instance": "https://<your-tenant-name>.b2clogin.com",
"ClientId": "<web-app-application-id>",
"Domain": "<your-b2c-domain>"
"CallbackPath": "/signin-oidc",
"SignUpSignInPolicyId": "B2C_1_test",
"ResetPasswordPolicyId": "B2C_1_test2",
"EditProfilePolicyId": "B2C_1_test1"
},
References:
ASP.NET MVC 3 - Handling Not Found
(c-sharpcorner.com)
NetCoreWeb/NetCoreB2C at master |
(github.com)
Using Azure B2C with MVC, .NET Core 3.1 - Stack Overflow
Related
I've already got an existing Blazor WebAssembly app and I'm attempting to add authentication with Azure Active Directory.
I've added the Microsoft.Authentication.WebAssembly.Msal nuget.
In my server's Program.cs, I've added the following code:
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
options.ProviderOptions.LoginMode = "redirect";
});
And I've added the following to my appsettings.json
"AzureAd": {
"Instance": "xxxxxxxxxxx",
"Domain": "xxxxxxxxxxx",
"TenantId": "xxxxxxxxxxx",
"ClientId": "xxxxxxxxxxx",
"CallbackPath": "xxxxxxxxxxx"
},
I'm struggling to understand what else I need to add so that when I run the app, I get the Microsoft sign in screen.
You need to require authorization for parts of the application, or for the entire app. By default, all routes inside the application are open to the public. If you want to shield any of these routes, you need to explicitly ask for authorization.
How to do this is documented here: Secure ASP.NET Core Blazor WebAssembly.
In Blazor WebAssembly apps, authorization checks can be bypassed because all client-side code can be modified by users. The same is true for all client-side app technologies, including JavaScript SPA frameworks or native apps for any operating system.
Always perform authorization checks on the server within any API endpoints accessed by your client-side app.
If you host the app on a hosting option like a Static Web App, you can have the Azure platform enforce authorization without having to implement anything manually.
Authenticate and authorize Static Web Apps.
You can create a new blazor web assemebly application and choose Microsoft identity platform and then modify the appsettings.json file.
You need to add 3 parts, authentication injection in Program.cs, configurations in appsettings.json, and the module for sign view, 2 of them you already had, and the left is the sign in/out button in the top navigation bar, so that you can click it to redirect to Microsoft sign in page. You can create the template project and copy the razor components into your project.
LoginDisplay.razor:
#using Microsoft.AspNetCore.Components.Authorization
#using Microsoft.AspNetCore.Components.WebAssembly.Authentication
#inject NavigationManager Navigation
#inject SignOutSessionStateManager SignOutManager
<AuthorizeView>
<Authorized>
Hello, #context.User.Identity?.Name!
<button class="nav-link btn btn-link" #onclick="BeginLogout">Log out</button>
</Authorized>
<NotAuthorized>
Log in
</NotAuthorized>
</AuthorizeView>
#code{
private async Task BeginLogout(MouseEventArgs args)
{
await SignOutManager.SetSignOutState();
Navigation.NavigateTo("authentication/logout");
}
}
I'm trying to create an MS Powerapp Custom Connector to access an ASP.NET core WebAPI, which is protected by Azure AD using the Microsoft.Identity.Web package. But no matter how I try to set things up, I'm always getting a 401 when trying to access the API via the connector.
So my setup looks like this:
Azure App registrations
I have registered two apps in Azure App Registrations. One for the API and one for the Powerapp Connector.
For the API registration I only configured settings under 'Expose an API'. I set an Application ID URI
api://f9****ca-****-****-****-3d30e9e*****
and added a scope
api://f9****ca-****-****-****-3d30e9e*****/Employees.Read.All
I also added an authorized client application using the ID of the App registration for the Powerapp (config below).
The app registration for the Powerapp is configured as follows:
For authentication the Web platform is added with redirect URI of https://global.consent.azure-apim.net/redirect.
Under 'Certificates & secrets' I added a client secret.
Under 'Api permissions' I added a permission for the scope of the API api://f9****ca-****-****-****-3d30e9e*****/Employees.Read.All as Delegated permission.
Powerapp Custom Connector config
The security tab of my custom connector is configured as follows:
Setting
Value
Auth type
OAuth 2.0
Identity Provider
Azure Active Directory
Client id
<Client ID of App reg for Powerapp>
Client Secret
<Client secret of App reg for Powerapp>
Login URL
https://login.windows.net
Tenant ID
<AAD Tenant ID>
Resource URL
api://f9****ca-****-****-****-3d30e9e***** <Application ID URI of App reg for API>
Scope
api://f9****ca-****-****-****-3d30e9e*****/Employees.Read.All
ASP.net core (3.1) Web App
I'm using the Microsoft.Identity.Web nuget package.
In my app config I added the following:
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "<Client ID of app reg for API>",
"TenantId": "<Tenant ID>"
}
The startup class looks like this:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
My controller is just decorated with the [Authorize] attribute.
Now, when I try to test an operation on the custom connector the WebAPI allways returns a 401 Unauthorized and I can't for the life of me figure out why.
I get see, that the request header has a Bearer token for the user I'm using to create the connection.
So a token is issued, but somehow the WebApi deems it invalid.
Interestingly the audience in that token is https://apihub.azure.com. Shouldn't it be the client id of the app reg? Anyway, even if I add that audience to the valid audiences in my WebAPI, I still get the 401...
Is there anything I am missing here? Any help would be really appreciated.
You forgot to add the Authenction middleware.
app.UseAuthentication();
app.UseAuthorization();
I'm in the process of updating an Asp.Net Core 2.2 application to 3.1.
We use Microsoft.Identity.Web to handle Azure AD authentication. I changed our security configuration as as follow:
ConfigureSerivces
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();
services.AddAuthentication()
.AddScheme<ApiKeyAuthenticationSchemeOptions, ApiKeyAuthenticationHandler
(AuthenticationSchemes.ApiKey, null);
And Configure
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<LogUsernameMiddleware>();
app.UseEndpoints(p =>
{
p.MapControllers();
});
But is throwing the following exception
System.InvalidOperationException
HResult=0x80131509
Message=No authentication handler is registered for the scheme 'AzureADJwtBearer'. The registered schemes are: Bearer, ApiKey. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("AzureADJwtBearer",...)?
Source=Microsoft.AspNetCore.Authentication.Core
StackTrace:
at Microsoft.AspNetCore.Authentication.AuthenticationService.<AuthenticateAsync>d__13.MoveNext() in /_/src/Http/Authentication.Core/src/AuthenticationService.cs:line 67
Not sure what part is not registering the authentication/authorization settings.
Thank you,
Problem was in our code, We were using a class with const string to return either ApiKey, AzureADJwtBearer or All as AuthenticationSchemes for controllers but AzureADJwtBearer as been replaced with just Bearer.
Thank you,
I have a project that needs to be updated at .net core 3.1. The problem is that i don't know how to use this new feature from 3.1. I have my Identity Server Settings in appsettings.development.json, like this:
"IdentityServerSettings": {
"TokenUrl": "https://esample/token",
"ClientId": "xxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxx",
"ClientSecret": "yyyyy-yyyyy-yyyyy-yyyyy-yyyyyyyyy",
"GrantType": "credentials",
"Scope": "scope"
}
Here is the Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
var identityServerSettingsSection = this.Configuration.GetSection("IdentityServerSettings");
services.AddIdentityServer()
// here i need to app those properties from json
}
Here is how i read them from json file
identityServerSettingsSection.GetValue<string>("ClientId")
Thanks in advance!
If you want to read the different attributes of the section IdentityServerSettings you can do it like this, suppose you want to read ClientId.
this.Configuration.GetSection("IdentityServerSettings").GetSection("ClientId");
Or if you want to read all the attributes you can use the option pattern.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1
you can add identityserver like this
services.AddIdentityServer(Configuration);
which Configuration is IConfiguration. and for appsetting.json follow this IdentityServer Options
We are currently migrating an existing ASP.NET Core 2.2 web application to 3.0 So far we've got most things working, except session storage.
We had this fully working in v2.2 as we used it to hold the current logged in user's details. Now that we've upgraded to v3.0 it no longer works.
Here's the middleware code.
public void ConfigureServices(IServiceCollection services)
{
// configure Razor pages, MVC, authentication here
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
//prevent session storage from being accessed from client script
//i.e. only server side code (added security)
options.Cookie.HttpOnly = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
}
N.B. I've removed the rest of the middleware code for clarity.
I've tried moving the app.SetSession() line to the top of the method in case the order of execution was the problem but this has made no difference.
When I hover over the HttpContent.Session property in the debugger I get the following error:
HttpContext.Session threw an exception of type System.InvalidOperationException
How do I enable Session storage in ASP.NET Core 3.0?
I've just tried adding the app.UseSession() to the top of the method and it's working now. It definitely didn't work before but it's working now and that's the main thing.