Using Azure B2C with MVC, .NET Core 3.1

馋奶兔 提交于 2021-02-11 09:10:19

问题


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.OptionsFactory1.Create(String name) at Microsoft.Extensions.Options.OptionsMonitor1.<>c__DisplayClass11_0.b__0() at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue() at System.Lazy1.get_Value() at Microsoft.Extensions.Options.OptionsCache1.GetOrAdd(String name, Func1 createOptions) at Microsoft.Extensions.Options.OptionsMonitor1.Get(String name) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.InitializeAsync(AuthenticationScheme scheme, HttpContext 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)


回答1:


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


来源:https://stackoverflow.com/questions/60999720/using-azure-b2c-with-mvc-net-core-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!