该错误通常出现在配置问题或在处理响应时出现问题。如果您遇到此错误,请检查您的 OIDC 配置和对应客户端的配置。您还可以通过查看 OpenIdConnect 处理程序是否已成功处理响应来检查问题是否出现在响应处理中。
以下是解决方案的示例代码:
Startup.cs
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Authority = "https://localhost:5001/";
options.ClientId = "blazorwasmclient";
options.ClientSecret = "blazorclientsecret";
options.ResponseType = "code";
options.UsePkce = true;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("phone");
options.Scope.Add("api.read");
options.Scope.Add("api.write");
options.CallbackPath = "/signin-oidc";
options.SignedOutCallbackPath = "/signout-callback-oidc";
options.RemoteSignOutPath = "/signout-oidc";
options.SaveTokens = true;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
});
Index.razor
@page "/"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
Hello, @context.User.Identity.Name!
You are authorized to view this page.
如果配置正确,但仍遇到此问题,请尝试使用以下代码在 Index.razor 中获取令牌:
@using System.IdentityModel.Tokens.Jwt
@using