配置 OIDC 客户端:打开 Startup.cs 文件并添加以下代码:
services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }).AddCookie(options => { options.Cookie.SameSite = SameSiteMode.None; }).AddOpenIdConnect(options => { options.Authority = "https://localhost:5001"; options.ClientId = "blazor_oidc"; options.ClientSecret = "blazor_oidc_secret"; options.ResponseType = "code"; options.Scope.Add("openid"); options.Scope.Add("profile"); options.SaveTokens = true; });
在 Index.razor 页面中添加以下代码:
@page "/" @using Microsoft.AspNetCore.Components.WebAssembly.Authentication @inject SignOutSessionStateManager SignOutManager @implements IDisposable
Hello, @context.User.Identity.Name!
@code { private IDisposable stateChanged;
protected override void OnInitialized()
{
stateChanged = SignOutManager.SubscribeToSignOutState((state) =>
{
if (state) // logout completion
{
// refresh the page to ensure a completely new circuit
NavigationManager.NavigateTo("/authentication/logout");
}
});
base.OnInitialized();
}
public void Dispose()
{
stateChanged.Dispose();
}
private async Task StartAuthentication()
{
var returnUrl = NavigationManager.ToAbsoluteUri(NavigationManager.Uri).ToString();
var options = new AuthenticationOptions
{
AuthenticationPaths = new AuthenticationPaths
{
Login = "/authentication/login",
Logout = "/authentication/logout",
LogInFailed = "/authentication/login-failed"
},
ProviderOptions = new List
{
new OpenIdConnectOptions
{
SignInScheme = "Cookies",
Authority