ASP.NET Core 中的 Azure AD B2C

问题描述 投票:0回答:1

我正在尝试将 Azure AD B2C 集成到 ASP.net core MVC 应用程序中。它最初显示登录页面,当输入用户名和密码后单击“登录”时,它会进入循环。当在浏览器中单击“停止加载此页面”图标时,它显示主页“处理您的请求时发生错误”。 (详情关联失败)。

output

程序.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C"));
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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.UseRouting();

app.UseAuthorization();
app.UseAuthentication();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();

在控制台中重复显示以下日志。

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter:信息:IDX10245:从经过验证的令牌创建声明身份:“[类型为“Microsoft.IdentityModel.JsonWebTokens.JsonWebToken”的 PII”已隐藏。有关更多详细信息,请参阅 https://aka.ms/IdentityModel/PII。]'。

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter:信息:IDX21305:OpenIdConnectProtocolValidationContext.ProtocolMessage.Code 为 null,OpenIdConnect 响应中没有要验证的“代码”。

Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter:信息:IDX21310:OpenIdConnectProtocolValidationContext.ProtocolMessage.AccessToken 为 null,OpenIdConnect 响应中没有要验证的“令牌”。

asp.net asp.net-core-mvc azure-ad-b2c
1个回答
0
投票

以下 ASP .NET Core 代码用于使用 Azure AD B2C 进行身份验证和授权。 Microsoft 身份服务用于 Azure AD B2C,并为下游 API 调用设置令牌获取。感谢 @Sridevi 提供了使用 Azure AD B2C 在您自己的 Web 应用程序中启用身份验证的链接。

Startup.cs

using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Identity.Web; using Microsoft.Identity.Web.UI; using TestApp.Infrastructure; using TestApp.Proxy; namespace TestApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Unspecified; options.HandleSameSiteCookieCompatibility(); }); services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C")) .EnableTokenAcquisitionToCallDownstreamApi(new string[] { Configuration["TestService:Scopes"] }) .AddDistributedTokenCaches(); services.AddDistributedMemoryCache(); // for other options see https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization services.AddRazorPages() .AddMicrosoftIdentityUI() .AddMvcOptions(options => options.Filters.Add(typeof(ReauthenticationRequiredFilter))); services.AddOptions(); services.Configure<OpenIdConnectOptions>(Configuration.GetSection("AzureAdB2C")); services.AddTransient<TestServiceProxy>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment 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.UseRouting(); app.UseAuthorization(); app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } }

_Layout.cshtml

@using System.Security.Principal <ul class="navbar-nav"> @if (User.Identity.IsAuthenticated) { <li class="nav-item"> <span class="navbar-text text-dark">Hello @User.Identity.Name!</span> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="EditProfile">Edit Profile</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a> </li> } else { <li class="nav-item"> <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a> </li> } </ul>
在 B2C 租户中创建了一个名为 

B2C_1_SUSI注册并登录

 用户流程,如下所示:

enter image description here

注册一个 Azure AD B2C 应用程序并在

Web

 平台中添加重定向 URI:

enter image description here

appSettings.json:

{ "AzureAdB2C": { "Instance": "https://b2ctenant.b2clogin.com", "Domain": "b2ctenant.onmicrosoft.com", "ClientId": "appId", "CallbackPath": "/signin-oidc", "SignedOutCallbackPath": "/signout/user_flow_name", "SignUpSignInPolicyId": "user_flow_name", "ResetPasswordPolicyId": "B2C_1_PasswordReset", "EditProfilePolicyId": "B2C_1_ProfileEdit", // To call an API "ClientSecret": "secret", "ClientCertificates": [ ] }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "Kestrel": { "Endpoints": { "Http": { "Url": "https://localhost:44349" } } }, "TestService": { "BaseUrl": "https://localhost:5001", "Scopes": "openid" } }

输出: enter image description here

enter image description here

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.