问题描述
我有一个 Angular 应用程序,它使用 OpenID 对用户进行身份验证,其中我可以访问应该用于对其他服务进行身份验证的 access_token。
我目前正在使用 OAuth/OpenID 的验证码流程
我正在尝试使用该 access_token 对 .NET Core Web API 上的用户进行身份验证。 我在这里所做的任何设置组合似乎都无法让我更接近解决方案。
Startup.cs
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme,options =>
{
options.Authority = oauthOptions.Authority;
options.ClientId = oauthOptions.ClientId;
options.ClientSecret = oauthOptions.ClientSecret;
options.ResponseType = OpenIdConnectResponseType.Code;
options.UsePkce = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Savetokens = true;
oauthOptions.Scopes.ForEach(scope => options.Scope.Add(scope));
});
我感谢任何有关此的指导/链接。
解决方法
在这种情况下,您最可能需要的是 JWT 不记名身份验证或令牌自省库,它根据身份提供者验证访问令牌。
对于 JWT,这是通过 Microsoft.AspNetCore.Authentication.JwtBearer
NuGet 包提供的,可以这样使用:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://url.to.your/identity-provider";
options.Audience = /* your expected audience - e.g. guid or resource */;
});
通过这种方式,您可以在 SPA 应用程序中获取和更新 JWT Bearer 访问令牌,并将经过身份验证的请求发送到 API 后端(使用 Authorization: Bearer ...
标头)。
如果您的身份提供者使用参考令牌(即,它们不包含身份验证信息,而是需要用于从身份提供者获取身份验证信息),您将需要使用令牌自省。这是 - 例如 - 由第三方库提供,如 IdentityModel.AspNetCore.OAuth2Introspection
使用 IdentityModel.AspNetCore.OAuth2Introspection
的示例:
services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
.AddOAuth2Introspection(options =>
{
options.Authority = "https://url.to.your/identity-provider";
// Introspection requires client credentials to authenticate the requests
options.ClientId = "client_id_for_introspection_endpoint";
options.ClientSecret = "client_secret_for_introspection_endpoint";
});