【发布时间】:2021-11-02 19:01:15
【问题描述】:
我在 blazor 项目中遇到了 OpenIdConnect 身份验证问题。如果登录失败或在登录过程中启动应用程序时发生任何异常,则应用程序将控制重定向到 error.razor 页面,因为用户未通过身份验证应用程序再次尝试从错误页面登录,而不是显示错误消息(身份验证之间的无限循环启动和error.razor)。我想从身份验证页面中排除错误页面。我做了很多搜索,但没有找到我的问题的解决方案
public void ConfigureServices(IServiceCollection services)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
// Instead of using the default validation (validating against a single issuer value, as we do in
// line of business apps), we inject our own multitenant validation logic
ValidateIssuer = false
// If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
//IssuerValidator = (issuer, securityToken, validationParameters) => {
// if (myIssuerValidationLogic(issuer)) return issuer;
//}
};
options.Events = ConfigureOpenIdConnectEvents(services);
});
}
private OpenIdConnectEvents ConfigureOpenIdConnectEvents(IServiceCollection services)
{
return new OpenIdConnectEvents
{
OnTicketReceived = context => Task.CompletedTask,
OnAuthenticationFailed = context =>
{
if (CurrentEnvironment.IsDevelopment()) return Task.CompletedTask;
context.Response.Redirect("/Error");
context.HandleResponse(); // Suppress the exception
return Task.CompletedTask;
},
// If your application needs to authenticate single users, add your user validation below.
OnTokenValidated = context =>
{
var client = Client;
var claims = new List<Claim>
{
new Claim("ClientId", client.Id.ToString()),
};
var appIdentity = new ClaimsIdentity(claims);
context.Principal.AddIdentity(appIdentity);
return Task.CompletedTask;
}
};
}
Error.Razor 页面
@page "/error"
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
【问题讨论】:
标签: c# asp.net-core blazor openid-connect blazor-server-side