要在 Blazor WebAssembly 项目中使用 JWT Bearer 身份验证,你需要在服务端项目中配置身份验证并将 JWT Token 传递到客户端项目中。下面是一个解决方法,其中包含了相关的代码示例:
Microsoft.AspNetCore.Authentication.JwtBearer
包:dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// 配置 JWT Bearer 身份验证的相关参数
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your_issuer",
ValidAudience = "your_audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_security_key"))
};
});
// ...
}
// ...
}
Program.cs
文件中,将 JWT Token 传递到客户端:using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
public class Program
{
// ...
public static async Task Main(string[] args)
{
// ...
builder.Services.AddHttpClient("your_server_client", client => client.BaseAddress = new Uri("your_server_base_url"))
.AddHttpMessageHandler();
builder.Services.AddScoped(sp => sp.GetRequiredService()
.CreateClient("your_server_client"));
builder.Services.AddOidcAuthentication(options =>
{
options.ProviderOptions.Authority = "your_authority";
options.ProviderOptions.ClientId = "your_client_id";
options.ProviderOptions.DefaultScopes.Add("your_scopes");
})
.AddAccountClaimsPrincipalFactory();
// ...
}
// ...
}
在上述代码中,你需要根据实际情况替换以下内容:
your_issuer
- JWT Token 的发行者(Issuer)your_audience
- JWT Token 的受众(Audience)your_security_key
- 用于验证 JWT Token 签名的密钥your_server_base_url
- 服务器项目的基本 URLyour_server_client
- 服务器项目的 HttpClient 名称your_authority
- OIDC 认证服务器的 URLyour_client_id
- OIDC 客户端的 IDyour_scopes
- OIDC 客户端的作用域这样配置之后,你就可以在 Blazor WebAssembly 客户端项目中使用 JWT Bearer 身份验证了。