【发布时间】:2021-04-22 02:22:36
【问题描述】:
目前我有三个独立的服务器。客户端在:5001,API 在:5002 和 IdentityServer 在:5003。我可以使用@attribute [Authorize] 对我的 Blazor 页面进行身份验证,但是当我调用 API 时出现 401 错误。如果我将 token_id 传递给邮递员并向其验证的 API 服务器发出请求。如果我从 Blazor 客户端发出请求,它将失败。我已将 CORS 列入白名单以排除此问题。如果我通过以下方式删除 API 上的受众检查:
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
有效
客户端程序.cs
builder.Services.AddHttpClient("api")
.AddHttpMessageHandler(sp =>
{
var handler = sp.GetService<AuthorizationMessageHandler>()
.ConfigureHandler(
authorizedUrls: new[] { "https://localhost:5002" },
scopes: new[] { "coredesk" });
return handler;
});
builder.Services.AddScoped(
sp => sp.GetService<IHttpClientFactory>().CreateClient("api"));
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("oidc", options.ProviderOptions);
});
客户端 appsettings.json
{
"oidc": {
"Authority": "https://localhost:5003/",
"ClientId": "coredesk",
"DefaultScopes": [
"openid",
"profile",
"coredesk"
],
"PostLogoutRedirectUri": "/",
"ResponseType": "code"
}
}
API 启动.cs
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:5003";
options.Audience = "coredesk";
});
IdentityServer Config.cs
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable<ApiResource> Apis =>
new ApiResource[]
{
new ApiResource("coredesk", "CoreDesk API")
};
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("coredesk"),
};
public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "coredesk",
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = true,
RequireClientSecret = false,
AllowedCorsOrigins = { "https://localhost:5001", "https://localhost:5002" },
AllowedScopes = { "openid", "profile", "coredesk" },
RedirectUris = { "https://localhost:5001/authentication/login-callback" },
PostLogoutRedirectUris = { "https://localhost:5001/" },
Enabled = true
},
};
【问题讨论】:
-
当您收到 401 错误时,WWW-Authenticate 响应标头会说什么?错误示例如下所示:HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer error="invalid_token", error_description="签名无效"
-
如果我删除 api 中的 Authorize 属性并运行调试器。我遵循的 Microsoft 文档和指南并未显示您必须将 Token 添加到标题中。我认为这是因为您不会将令牌存储在浏览器中 medium.com/@marcodesanctis2/…
标签: asp.net blazor identityserver4