这一系列我们都采用这样的方式,先大概看下协议,也就是需求描述,然后看idsv4怎么实现的,这样可以加深理解。
元数据接口的协议地址如下:
https://openid.net/specs/openid-connect-discovery-1_0.html
该协议定义了一套标准,用户能够获取到oidc服务的基本信息,包括OAuth2.0相关接口地址。
先了解一下Webfinger这个概念。
WebFinger可以翻译成网络指纹,它定义了一套标准,描述如何通过标准的HTTP方法去获取网络实体的资料信息。WebFinger使用JSON来描述实体信息。
https://tools.ietf.org/html/rfc7033
可选协议。
定义了如何获取oidc服务元数据。如果客户端明确知道oidc服务的地址,可以跳过此部分。
个人理解是存在多个oidc服务的情况,可以部署一个webfinger服务,根据资源请求,路由到不同的oidc服务。
通常来说,我们只有一个oidc服务,我看了一下idsv4也没有实现这一部分协议,这里了解一下就可以了。
必选协议。
用于描述oidc服务各接口地址及其他配置信息。
必须校验issuer与请求地址是否一致
启个idsrv服务调用试一下,返回结果如图

详细信息如下。
{
"issuer": "https://localhost:10000",
"jwks_uri": "https://localhost:10000/.well-known/openid-configuration/jwks",
"authorization_endpoint": "https://localhost:10000/connect/authorize",
"token_endpoint": "https://localhost:10000/connect/token",
"userinfo_endpoint": "https://localhost:10000/connect/userinfo",
"end_session_endpoint": "https://localhost:10000/connect/endsession",
"check_session_iframe": "https://localhost:10000/connect/checksession",
"revocation_endpoint": "https://localhost:10000/connect/revocation",
"introspection_endpoint": "https://localhost:10000/connect/introspect",
"device_authorization_endpoint": "https://localhost:10000/connect/deviceauthorization",
"frontchannel_logout_supported": true,
"frontchannel_logout_session_supported": true,
"backchannel_logout_supported": true,
"backchannel_logout_session_supported": true,
"scopes_supported": [
"openid",
"profile",
"userid",
"username",
"email",
"mobile",
"api",
"offline_access"
],
"claims_supported": [
"sub",
"updated_at",
"locale",
"zoneinfo",
"birthdate",
"gender",
"preferred_username",
"picture",
"profile",
"nickname",
"middle_name",
"given_name",
"family_name",
"website",
"name",
"userid",
"username",
"email",
"mobile"
],
"grant_types_supported": [
"authorization_code",
"client_credentials",
"refresh_token",
"implicit",
"password",
"urn:ietf:params:oauth:grant-type:device_code"
],
"response_types_supported": [
"code",
"token",
"id_token",
"id_token token",
"code id_token",
"code token",
"code id_token token"
],
"response_modes_supported": [
"form_post",
"query",
"fragment"
],
"token_endpoint_auth_methods_supported": [
"client_secret_basic",
"client_secret_post"
],
"id_token_signing_alg_values_supported": [
"RS256"
],
"subject_types_supported": [
"public"
],
"code_challenge_methods_supported": [
"plain",
"S256"
],
"request_parameter_supported": true
}
idsv还注入这样一个接口:DiscoveryKeyEndpoint,尝试发现返回了一组密钥。协议内容如下。
https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41
GET /.well-known/openid-configuration/jwks,返回结果如下
接口地址都在Constants.cs这个文件,ProtocalRoutePaths这个类里面定义的。现在知道为什么接口地址是.well-known/openid-configuration这样奇怪的一个路由了,这是oidc协议定的(对,都是产品的锅)。

代码很长,但是逻辑很简单,就是组装协议规定的所有地址和信息。
需要注意的支持的claims、支持的scope等信息是遍历所有IdentityResource、ApiResource动态获取的。
基本上每个接口都可以配置是否显示在元数据文档中。
public async Task<IEndpointResult> ProcessAsync(HttpContext context)
{
_logger.LogTrace("Processing discovery request.");
if (!HttpMethods.IsGet(context.Request.Method))
{
_logger.LogWarning("Discovery endpoint only supports GET requests");
return new StatusCodeResult(HttpStatusCode.MethodNotAllowed);
}
_logger.LogDebug("Start discovery request");
if (!_options.Endpoints.EnableDiscoveryEndpoint)
{
_logger.LogInformation("Discovery endpoint disabled. 404.");
return new StatusCodeResult(HttpStatusCode.NotFound);
}
var baseUrl = context.GetIdentityServerBaseUrl().EnsureTrailingSlash();
var issuerUri = context.GetIdentityServerIssuerUri();
_logger.LogTrace("Calling into discovery response generator: {type}", _responseGenerator.GetType().FullName);
var response = await _responseGenerator.CreateDiscoveryDocumentAsync(baseUrl, issuerUri);
return new DiscoveryDocumentResult(response, _options.Discovery.ResponseCacheInterval);
}
public virtual async Task<Dictionary<string, object>> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri)
{
var entries = new Dictionary<string, object>
{
{ OidcConstants.Discovery.Issuer, issuerUri }
};
if (Options.Discovery.ShowKeySet)
{
if ((await Keys.GetValidationKeysAsync()).Any())
{
entries.Add(OidcConstants.Discovery.JwksUri, baseUrl + Constants.ProtocolRoutePaths.DiscoveryWebKeys);
}
}
if (Options.Discovery.ShowEndpoints)
{
if (Options.Endpoints.EnableAuthorizeEndpoint)
{
entries.Add(OidcConstants.Discovery.AuthorizationEndpoint, baseUrl + Constants.ProtocolRoutePaths.Authorize);
}
if (Options.Endpoints.EnableTokenEndpoint)
{
entries.Add(OidcConstants.Discovery.TokenEndpoint, baseUrl + Constants.ProtocolRoutePaths.Token);
}
if (Options.Endpoints.EnableUserInfoEndpoint)
{
entries.Add(OidcConstants.Discovery.UserInfoEndpoint, baseUrl + Constants.ProtocolRoutePaths.UserInfo);
}
if (Options.Endpoints.EnableEndSessionEndpoint)
{
entries.Add(OidcConstants.Discovery.EndSessionEndpoint, baseUrl + Constants.ProtocolRoutePaths.EndSession);
}
if (Options.Endpoints.EnableCheckSessionEndpoint)
{
entries.Add(OidcConstants.Discovery.CheckSessionIframe, baseUrl + Constants.ProtocolRoutePaths.CheckSession);
}
if (Options.Endpoints.EnableTokenRevocationEndpoint)
{
entries.Add(OidcConstants.Discovery.RevocationEndpoint, baseUrl + Constants.ProtocolRoutePaths.Revocation);
}
if (Options.Endpoints.EnableIntrospectionEndpoint)
{
entries.Add(OidcConstants.Discovery.IntrospectionEndpoint, baseUrl + Constants.ProtocolRoutePaths.Introspection);
}
if (Options.Endpoints.EnableDeviceAuthorizationEndpoint)
{
entries.Add(OidcConstants.Discovery.DeviceAuthorizationEndpoint, baseUrl + Constants.ProtocolRoutePaths.DeviceAuthorization);
}
if (Options.MutualTls.Enabled)
{
var mtlsEndpoints = new Dictionary<string, string>();
if (Options.Endpoints.EnableTokenEndpoint)
{
mtlsEndpoints.Add(OidcConstants.Discovery.TokenEndpoint, baseUrl + Constants.ProtocolRoutePaths.MtlsToken);
}
if (Options.Endpoints.EnableTokenRevocationEndpoint)
{
mtlsEndpoints.Add(OidcConstants.Discovery.RevocationEndpoint, baseUrl + Constants.ProtocolRoutePaths.MtlsRevocation);
}
if (Options.Endpoints.EnableIntrospectionEndpoint)
{
mtlsEndpoints.Add(OidcConstants.Discovery.IntrospectionEndpoint, baseUrl + Constants.ProtocolRoutePaths.MtlsIntrospection);
}
if (Options.Endpoints.EnableDeviceAuthorizationEndpoint)
{
mtlsEndpoints.Add(OidcConstants.Discovery.DeviceAuthorizationEndpoint, baseUrl + Constants.ProtocolRoutePaths.MtlsDeviceAuthorization);
}
if (mtlsEndpoints.Any())
{
entries.Add(OidcConstants.Discovery.MtlsEndpointAliases, mtlsEndpoints);
}
}
}
if (Options.Endpoints.EnableEndSessionEndpoint)
{
entries.Add(OidcConstants.Discovery.FrontChannelLogoutSupported, true);
entries.Add(OidcConstants.Discovery.FrontChannelLogoutSessionSupported, true);
entries.Add(OidcConstants.Discovery.BackChannelLogoutSupported, true);
entries.Add(OidcConstants.Discovery.BackChannelLogoutSessionSupported, true);
}
if (Options.Discovery.ShowIdentityScopes ||
Options.Discovery.ShowApiScopes ||
Options.Discovery.ShowClaims)
{
var resources = await ResourceStore.GetAllEnabledResourcesAsync();
var scopes = new List<string>();
if (Options.Discovery.ShowIdentityScopes)
{
scopes.AddRange(resources.IdentityResources.Where(x => x.ShowInDiscoveryDocument).Select(x => x.Name));
}
if (Options.Discovery.ShowApiScopes)
{
var apiScopes = from api in resources.ApiResources
from scope in api.Scopes
where scope.ShowInDiscoveryDocument
select scope.Name;
scopes.AddRange(apiScopes);
scopes.Add(IdentityServerConstants.StandardScopes.OfflineAccess);
}
if (scopes.Any())
{
entries.Add(OidcConstants.Discovery.ScopesSupported, scopes.ToArray());
}
if (Options.Discovery.ShowClaims)
{
var claims = new List<string>();
claims.AddRange(resources.IdentityResources.Where(x => x.ShowInDiscoveryDocument).SelectMany(x => x.UserClaims));
foreach (var resource in resources.ApiResources)
{
claims.AddRange(resource.UserClaims);
foreach (var scope in resource.Scopes)
{
if (scope.ShowInDiscoveryDocument)
{
claims.AddRange(scope.UserClaims);
}
}
}
entries.Add(OidcConstants.Discovery.ClaimsSupported, claims.Distinct().ToArray());
}
}
if (Options.Discovery.ShowGrantTypes)
{
var standardGrantTypes = new List<string>
{
OidcConstants.GrantTypes.AuthorizationCode,
OidcConstants.GrantTypes.ClientCredentials,
OidcConstants.GrantTypes.RefreshToken,
OidcConstants.GrantTypes.Implicit
};
if (!(ResourceOwnerValidator is NotSupportedResourceOwnerPasswordValidator))
{
standardGrantTypes.Add(OidcConstants.GrantTypes.Password);
}
if (Options.Endpoints.EnableDeviceAuthorizationEndpoint)
{
standardGrantTypes.Add(OidcConstants.GrantTypes.DeviceCode);
}
var showGrantTypes = new List<string>(standardGrantTypes);
if (Options.Discovery.ShowExtensionGrantTypes)
{
showGrantTypes.AddRange(ExtensionGrants.GetAvailableGrantTypes());
}
entries.Add(OidcConstants.Discovery.GrantTypesSupported, showGrantTypes.ToArray());
}
if (Options.Discovery.ShowResponseTypes)
{
entries.Add(OidcConstants.Discovery.ResponseTypesSupported, Constants.SupportedResponseTypes.ToArray());
}
if (Options.Discovery.ShowResponseModes)
{
entries.Add(OidcConstants.Discovery.ResponseModesSupported, Constants.SupportedResponseModes.ToArray());
}
if (Options.Discovery.ShowTokenEndpointAuthenticationMethods)
{
var types = SecretParsers.GetAvailableAuthenticationMethods().ToList();
if (Options.MutualTls.Enabled)
{
types.Add(OidcConstants.EndpointAuthenticationMethods.TlsClientAuth);
types.Add(OidcConstants.EndpointAuthenticationMethods.SelfSignedTlsClientAuth);
}
entries.Add(OidcConstants.Discovery.TokenEndpointAuthenticationMethodsSupported, types);
}
var signingCredentials = await Keys.GetSigningCredentialsAsync();
if (signingCredentials != null)
{
var algorithm = signingCredentials.Algorithm;
entries.Add(OidcConstants.Discovery.IdTokenSigningAlgorithmsSupported, new[] { algorithm });
}
entries.Add(OidcConstants.Discovery.SubjectTypesSupported, new[] { "public" });
entries.Add(OidcConstants.Discovery.CodeChallengeMethodsSupported, new[] { OidcConstants.CodeChallengeMethods.Plain, OidcConstants.CodeChallengeMethods.Sha256 });
if (Options.Endpoints.EnableAuthorizeEndpoint)
{
entries.Add(OidcConstants.Discovery.RequestParameterSupported, true);
if (Options.Endpoints.EnableJwtRequestUri)
{
entries.Add(OidcConstants.Discovery.RequestUriParameterSupported, true);
}
}
if (Options.MutualTls.Enabled)
{
entries.Add(OidcConstants.Discovery.TlsClientCertificateBoundAccessTokens, true);
}
if (!Options.Discovery.CustomEntries.IsNullOrEmpty())
{
foreach (var customEntry in Options.Discovery.CustomEntries)
{
if (entries.ContainsKey(customEntry.Key))
{
Logger.LogError("Discovery custom entry {key} cannot be added, because it already exists.", customEntry.Key);
}
else
{
if (customEntry.Value is string customValueString)
{
if (customValueString.StartsWith("~/") && Options.Discovery.ExpandRelativePathsInCustomEntries)
{
entries.Add(customEntry.Key, baseUrl + customValueString.Substring(2));
continue;
}
}
entries.Add(customEntry.Key, customEntry.Value);
}
}
}
return entries;
}
然后是jwks描述信息的代码。关于加密的信息也是根据配置的SecuritKey去动态返回的。
这一节还是比较好理解的。总而言之就是oidc协议规定了,需要提供GET接口,返回所有接口的地址,以及相关配置信息。idsv4的实现方式就是接口地址根据协议规定的去拼接,其他配置项信息根据开发的配置去动态获取,然后以协议约定的JSON格式返回。
__EOF__