在我的 .NET Blazor 应用程序中,使用 Azure B2C 成功进行身份验证后(Azure 登录日志显示“成功”),返回错误页面并显示 URL
https://localhost: /signin-oidc
不幸的是,没有日志可以说明错误的原因。
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(10);
builder.Configuration.Bind("OpenIDConnect", options);
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async ctxt =>
{
logger.Info($"On Redirect To Identity Provider : {ctxt.Request.Host.Value}");
await Task.Yield();
},
OnAuthenticationFailed = async ctxt =>
{
logger.Info($"On Authentication Failed");
Console.WriteLine("On Authentication Failed");
await Task.Yield();
},
OnSignedOutCallbackRedirect = async ctxt =>
{
logger.Info($"On Signed Out Callback Redirect");
ctxt.HttpContext.Response.Redirect(ctxt.Options.SignedOutRedirectUri);
ctxt.HandleResponse();
await Task.Yield();
},
OnMessageReceived = async ctxt =>
{
logger.Info($"On Message Received : {ctxt.Request.Path.Value}");
},
OnAuthorizationCodeReceived = async context =>
{
logger.Info("Authorization Code Received");
Console.WriteLine("Authorization Code Received");
},
OnTokenValidated = async context =>
{
logger.Info("Token Validated");
Console.WriteLine("Token Validated");
},
OnRemoteFailure = async ctxt =>
{
logger.Info($"On Remote Failure : {ctxt.Failure?.Message}");
ctxt.Response.Redirect("/");
ctxt.HandleResponse();
Console.WriteLine("On Remote Failure");
},
OnTokenResponseReceived = async ctxt =>
{
logger.Info($"On Access Denied");
Console.WriteLine("OnTokenResponseReceived");
},
OnTicketReceived = async ctxt =>
{
logger.Info($"On Ticket Received : {ctxt.Request.Path.Value}");
}
);
日志记录
OnRedirectToIdentityProvider
事件,但OnRemoteFailure
或OnTokenResponseReceived
没有日志。
您能否建议我如何解决此错误或将其记录下来以供参考?
提前致谢。任何帮助表示赞赏。
我创建了一个示例 Blazor 服务器 (.NET 8) 应用程序并使用 Azure B2C 成功进行了身份验证。
我参考了这个博客来创建应用程序和配置Azure B2C身份验证。
确保您在
appsettings.json
中定义正确的策略名称、域或实例
appsettings.json:
{
"AzureAdB2C": {
"Instance": "https://{ Azure B2C Domain Name}.b2clogin.com/tfp/",
"ClientId": "<Client-Id>",
"CallbackPath": "/signin-oidc",
"Domain": "{ Azure B2C Domain Name}.onmicrosoft.com",
"SignUpSignInPolicyId": "B2C_1_Blazorsigninsingup",
"ResetPasswordPolicyId": "",
"EditProfilePolicyId": ""
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
ASPNETCORE_ENVIRONMENT
文件中的Development
设置为launchSettings.json
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7288;http://localhost:5056",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
程序.cs:
using blazorb2c.Components;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web.UI;
using Microsoft.Identity.Web;
using System.Reflection;
using System.Security.Claims;
using System.Linq.Dynamic.Core;
using blazorb2c.Components;
namespace BlazorAzureB2C
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var env = builder.Environment;
builder.Configuration.AddJsonFile($"appsettings{env.EnvironmentName}.json", optional: true);
builder.Configuration.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly(), true);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddMicrosoftIdentityConsentHandler();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<HttpContextAccessor>();
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async ctxt =>
{
await Task.Yield();
},
OnAuthenticationFailed = async ctxt =>
{
await Task.Yield();
},
OnSignedOutCallbackRedirect = async ctxt =>
{
ctxt.HttpContext.Response.Redirect(ctxt.Options.SignedOutRedirectUri);
ctxt.HandleResponse();
await Task.Yield();
},
OnTicketReceived = async ctxt =>
{
if (ctxt.Principal != null)
{
if (ctxt.Principal.Identity is ClaimsIdentity identity)
{
var colClaims = await ctxt.Principal.Claims.ToDynamicListAsync();
var IdentityProvider = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.microsoft.com/identity/claims/identityprovider")?.Value;
var Objectidentifier = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
var EmailAddress = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
var FirstName = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname")?.Value;
var LastName = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname")?.Value;
var AzureB2CFlow = colClaims.FirstOrDefault(
c => c.Type == "http://schemas.microsoft.com/claims/authnclassreference")?.Value;
var auth_time = colClaims.FirstOrDefault(
c => c.Type == "auth_time")?.Value;
var DisplayName = colClaims.FirstOrDefault(
c => c.Type == "name")?.Value;
var idp_access_token = colClaims.FirstOrDefault(
c => c.Type == "idp_access_token")?.Value;
}
}
await Task.Yield();
},
};
});
builder.Services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
}
}
}
将正确的重定向 URI 添加到您的 Azure B2C 应用程序注册中,如下所示。
检查您在
User flow
中是否使用了正确的 appsettings.json
名称。
现在我已成功通过 Azure B2C 身份验证。
输出: