简体   繁体   中英

Using Azure B2C with MVC, .NET Core 3.1

Could anyone provide some insight or new links on using Azure B2C with MVC, .NET Core 3.1. Most examples are based on Core 2.2

https://docs.microsoft.com/en-us/samples/azure-samples/active-directory-b2c-dotnetcore-webapp/an-aspnet-core-web-app-with-azure-ad-b2c/

However, it seems more than a few things are done differently with 3.1.

The error I encounter in 2.2 is:

System.ArgumentNullException: Value cannot be null. (Parameter 'uriString') at System.Uri..ctor(String uriString) at Microsoft.AspNetCore.Authentication.AzureADB2C.UI.AzureADB2COpenIdConnectOptionsConfiguration.BuildAuthority(AzureADB2COptions AzureADB2COptions) at Microsoft.AspNetCore.Authentication.AzureADB2C.UI.AzureADB2COpenIdConnectOptionsConfiguration.Configure(String name, OpenIdConnectOptions options) at Microsoft.Extensions.Options.OptionsFactory 1.Create(String name) at Microsoft.Extensions.Options.OptionsMonitor 1.<>c__DisplayClass11_0.b__0() at System.Lazy 1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy 1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy 1.CreateValue() at System.Lazy 1.get_Value() at Microsoft.Extensions.Options.OptionsCache 1.GetOrAdd(String name, Func 1 createOptions) at Microsoft.Extensions.Options.OptionsMonitor 1.Get(String name) at Microsoft.AspNetCore.Authentication.AuthenticationHandler 1.InitializeAsync(AuthenticationScheme scheme, Http Context context) at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

If you want to configure Azure AD B2C auth for your .net core application, you can use sdk Microsoft.AspNetCore.Authentication.AzureADB2C.UI . But please note that you need to choose the right sdk version according to the .net core version you use. For example, if you use .net core 2.2, the sdk version should be 2.2.0.

The detailed steps are as below

  1. Register a web application in Azure AD B2C tenant

  2. Implement Azure AD B2C auth in web application

    a. 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" }, ... }

    b.add the following code in the Startup.cs

     public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme) .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

    c. Implement sign in and sign out. The sdk has helped us implement sign-in and sign-out method. So we can directly use it. For example

my login.cshtml

@using System.Security.Principal
@using Microsoft.AspNetCore.Authentication.AzureADB2C.UI
@using Microsoft.Extensions.Options
@inject IOptionsMonitor<AzureADB2COptions> AzureADB2COptions

@{
    var options = AzureADB2COptions.Get(AzureADB2CDefaults.AuthenticationScheme);
}


<ul class="navbar-nav">
@if (User.Identity.IsAuthenticated)
{

            <li class="nav-item">
                <span class="nav-text text-dark">Hello @User.Identity.Name!</span>
            </li>

        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignOut">Sign out</a>
        </li>
}
else
{
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="AzureADB2C" asp-controller="Account" asp-action="SignIn">Sign in</a>
        </li>
}
</ul>
  1. Test在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM