这是完全可能的。对于 Blazor Web 程序集(前端托管模式),我们可以执行以下操作。
假设我们有一个正在运行的 IdentityServer 4https://localhost:5001
和一个运行 Blazor Web Assembly 的客户端 SPA 应用程序https://localhost:5003
对于 Identity Server,让我们配置一个新客户端。
new Client
{
ClientId = "spa",
ClientUri = "https://localhost:5003",
AllowedGrantTypes = GrantTypes.Code,
RequireClientSecret = false, // for auth code flow there is no secret required as it couldn't be securely stored in the front-end anyway
// where to redirect to after login
RedirectUris = { "https://localhost:5003/authentication/login-callback" },
// where to redirect to after logout
PostLogoutRedirectUris = { "https://localhost:5003/signout-callback-oidc" },
// CORS
AllowedCorsOrigins = { "https://localhost:5003" },
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
}
}
对于 Blazor 应用程序,假设我们已经创建了一个默认应用程序并选择了身份验证Store user accounts in-app
,以便它为登录功能创建样板并添加包
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="3.2.1" />
现在我们必须在 Program.cs 中配置 Blazor 客户端应用的 OpenId Connect 设置。
请注意,默认情况下可以读取 appsettings.json,builder.Configuration.Bind("Local", options.ProviderOptions);
为简单起见,我们可以手动硬编码设置。
builder.Services.AddOidcAuthentication(
options =>
{
//let's hardcode the values for now. We can enable reading from settings later.
//builder.Configuration.Bind("Local", options.ProviderOptions);
options.ProviderOptions.Authority = "https://localhost:5001";
options.ProviderOptions.ClientId = "spa";
options.ProviderOptions.DefaultScopes.Add("openid");
options.ProviderOptions.DefaultScopes.Add("profile");
options.ProviderOptions.DefaultScopes.Add("api1");
options.ProviderOptions.PostLogoutRedirectUri = "https://localhost:5003/counter";
options.ProviderOptions.RedirectUri = "https://localhost:5003/authentication/login-callback";
options.ProviderOptions.ResponseType = "code";
});
该配置应该足以让 blazor 应用程序重定向到 Identity Server 以询问凭据并在用户通过身份验证后存储令牌。