将Azure B2C与MVC,.NET Core 3.1结合使用 [英] Using Azure B2C with MVC, .NET Core 3.1

查看:53
本文介绍了将Azure B2C与MVC,.NET Core 3.1结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以提供有关将Azure B2C与MVC,.NET Core 3.1结合使用的见解或新链接.大多数示例基于Core 2.2

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)

解决方案

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

这篇关于将Azure B2C与MVC,.NET Core 3.1结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆