Blazor IdentityServer Authenthentication



目前我有三个独立的服务器。客户端:5001,API:5002, IdentityServer:5003。我可以使用@attribute [Authorize]验证我的Blazor页面,但当我调用API时,我得到401错误。如果我将token_id传递给postman并向API服务器发出请求,它将进行身份验证。如果我从我的Blazor客户端发出请求,它会失败。我已将CORS列入白名单,以排除这个问题。如果我用

删除api上的Audience检查
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};

客户机program.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 Startup.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
},
};

如果您查看AddJwtBearer的源代码,您会发现以下部分:

// If no authorization header found, nothing to process further
if (string.IsNullOrEmpty(authorization))
{
return AuthenticateResult.NoResult();
}
if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
{
token = authorization.Substring("Bearer ".Length).Trim();
}
// If no token found, no further work possible
if (string.IsNullOrEmpty(token))
{
return AuthenticateResult.NoResult();
}

这表明默认情况下(没有自定义)它要求在Authorization报头中提供令牌,如下所示:

GET /api/payments HTTP/1.1
Host: localhost:7001
Authorization: Bearer eyJhbGciOiJSUzI1NiIsIYwA...

为了进一步调试,我将删除authorize属性,然后在一个操作方法中放置一个断点,并检查claimsprprincipal用户对象包含的内容。

为了补充这个答案,我写了一篇博客文章,更详细地讨论了这个话题:ASP中JwtBearer身份验证问题的排除。网络核心

相关内容

  • 没有找到相关文章