首页 > 解决方案 > 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.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)

标签: c#asp.net-mvcazureasp.net-core-3.1

解决方案


如果要为 .net 核心应用程序配置 Azure AD B2C 身份验证,可以使用 sdk Microsoft.AspNetCore.Authentication.AzureADB2C.UI。但请注意,您需要根据您使用的 .net core 版本选择正确的 sdk 版本。比如你使用.net core 2.2,sdk版本应该是2.2.0。

详细步骤如下

  1. 在 Azure AD B2C 租户中注册 Web 应用程序

  2. 在 Web 应用程序中实现 Azure AD B2C 身份验证

    一个。在 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"
    },
    ...
    }
    
    

    湾。在 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。实现登录和注销。sdk 帮助我们实现了登录和注销方法。所以我们可以直接使用它。例如

我的 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. 测试 在此处输入图像描述

推荐阅读