在 Blazor Web 程序集客户端应用中使用 Auth0 注销后 ASP.NET 登录提示



我刚刚开始构造一个简单的 Web 程序集 ASP.NET 客户端 Web 应用程序,其身份验证由 Auth0 提供支持。

我发现有几篇文章引导您完成执行此操作所需的步骤,例如: https://auth0.com/blog/what-is-blazor-tutorial-on-building-webapp-with-authentication/

不幸的是,由于其中许多是编写的,因此似乎 Blazor 客户端项目已从面向 .NET Core 移植到 .NET 标准,因此无法安装所需的 NuGet 包:Microsoft.AspNetCore.Authentication.OpenIdConnect

相反,我从Microsoft中找到了一个教程,该教程使用Microsoft.AspNetCore.Components.WebAssembly.Authentication它包装了一些处理身份验证流所需的Javascript代码: https://learn.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/standalone-with-authentication-library?view=aspnetcore-3.1

我设法让它工作,但是当我注销并再次登录时,应用程序会自动进行身份验证,而无需将我带到 Auth0 登录页面。根据 OpenID Connect 规范,我需要发送一个可选的prompt参数login集,以强制显示登录屏幕(注销后我作为用户的期望(。

前面提到的Microsoft.AspNetCore.Authentication.OpenIdConnect库能够设置此参数:https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.openidconnect.openidconnectoptions.prompt?view=aspnetcore-3.0

据我所知,WebAssembly 库没有:https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.webassembly.authentication.oidcprovideroptions?view=aspnetcore-3.1

有谁知道解决方法?

Program.cs如下:

public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddOidcAuthentication(options =>
{
options.ProviderOptions.Authority = $"https://{builder.Configuration["Auth0:Domain"]}";
options.ProviderOptions.ClientId = builder.Configuration["Auth0:ClientId"];
options.ProviderOptions.ResponseType = builder.Configuration["Auth0:ResponseType"];
options.ProviderOptions.PostLogoutRedirectUri = "/";
});
await builder.Build().RunAsync();
}
}

我发现我需要显式调用logout端点: https://auth0.com/docs/api/authentication?javascript#logout

现在我已经创建了一个Logout组件并在其中添加了逻辑 - 我希望有更好的方法(例如,将其配置为AddOidcAuthentication的一部分,但我无法弄清楚(。

@inject NavigationManager Navigation
@inject SignOutSessionStateManager SignOutManager
@inject BaseAddress BaseAddress
@inject Auth0Config Auth0Config
<AuthorizeView>
<Authorized>
<button class=@($"{CssClass} btn btn-link") @onclick=BeginSignOut>Log out</button>
</Authorized>
</AuthorizeView>
@code {

[Parameter]
public string CssClass { get; set; }
private async Task BeginSignOut()
{
await SignOutManager.SetSignOutState();
Navigation.NavigateTo($"{Auth0Config.Authority}/v2/logout?client_id={Auth0Config.ClientId}&returnTo={BaseAddress.Url}authentication/logout");
}
}

最新更新