目錄 "identityserver4源碼解析_1_項目結構" "identityserver4源碼解析_2_元數據介面" "identityserver4源碼解析_3_認證介面" "identityserver4源碼解析_4_令牌發放介面" "identityserver4源碼解析_5_查詢用戶信 ...
目錄
- identityserver4源碼解析_1_項目結構
- identityserver4源碼解析_2_元數據介面
- identityserver4源碼解析_3_認證介面
- identityserver4源碼解析_4_令牌發放介面
- identityserver4源碼解析_5_查詢用戶信息介面
- identityserver4源碼解析_6_結束會話介面
- identityserver4源碼解析_7_查詢令牌信息介面
- identityserver4源碼解析_8_撤銷令牌介面
協議
這一系列我們都採用這樣的方式,先大概看下協議,也就是需求描述,然後看idsv4怎麼實現的,這樣可以加深理解。
元數據介面的協議地址如下:
摘要
該協議定義了一套標準,用戶能夠獲取到oidc服務的基本信息,包括OAuth2.0相關介面地址。
Webfinger - 網路指紋
先瞭解一下Webfinger這個概念。
WebFinger可以翻譯成網路指紋,它定義了一套標準,描述如何通過標準的HTTP方法去獲取網路實體的資料信息。WebFinger使用JSON來描述實體信息。
查詢oidc服務元數據 - OpenID Provider Issuer Discovery
可選協議。
定義瞭如何獲取oidc服務元數據。如果客戶端明確知道oidc服務的地址,可以跳過此部分。
個人理解是存在多個oidc服務的情況,可以部署一個webfinger服務,根據資源請求,路由到不同的oidc服務。
通常來說,我們只有一個oidc服務,我看了一下idsv4也沒有實現這一部分協議,這裡瞭解一下就可以了。
查詢oidc服務配置信息 - OpenID Provider Configuration Request
必選協議。
用於描述oidc服務各介面地址及其他配置信息。
GET /.well-known/openid-configuration HTTP/1.1
Host: example.com
必須校驗issuer與請求地址是否一致
啟個idsrv服務調用試一下,返回結果如圖
詳細信息如下。
{
"issuer": "https://localhost:10000", //頒發者地址
"jwks_uri": "https://localhost:10000/.well-known/openid-configuration/jwks", //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": [ //支持的授權範圍,scope
"openid",
"profile",
"userid",
"username",
"email",
"mobile",
"api",
"offline_access" //token過期可用refresh_token刷新換取新token
],
"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", //刷新token
"implicit", //隱式流程, 一般用於單頁應用javascript客戶端
"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", //form-post提交
"query", //get提交
"fragment" //fragment提交
],
"token_endpoint_auth_methods_supported": [ //發放令牌介面支持的認證方式
"client_secret_basic", //basic
"client_secret_post" //post
],
"id_token_signing_alg_values_supported": [ //身份令牌加密演算法
"RS256"
],
"subject_types_supported": [
"public"
],
"code_challenge_methods_supported": [
"plain",
"S256"
],
"request_parameter_supported": true
}
JWK - Json Web Keys
idsv還註入這樣一個介面:DiscoveryKeyEndpoint,嘗試發現返回了一組密鑰。協議內容如下。
GET /.well-known/openid-configuration/jwks,返回結果如下
{
"keys": [
{
"kty": "RSA",
"use": "sig",
"kid": "LS-EQOr-3BkalkkUVh8q7Q",
"e": "AQAB",
"n": "08BLLaTz4JrTYmE4bZ9c7oKVrZKLy3KfGT5mmnslhl41nk_EV_8OUdL8wMXunC2KERdnsy5XYk4aw3LlvxZDIvjxO9PEblPsoap-WErdi9GVyAv-NJ6eJQy3S7FRSkvzQYBsLnCKm5wu0kjdQBVUCFJ7wfiZ9ayY7pH7K10qN2Utvt-qsCLUy0cJ0StuP_rquefp7_XhUw3A8IIA8P6DjfZIbpwrVjOeVWoI_ZKIwfxShghOAKBDLyQuC2PhozsqZ7HvGEeAPm06YPMWQVbE9_LBn2j_Ul_VBUWc9KfBNOzk_BMQHyF2NUlwMtqMUEcwK_hpjEeo62O_aFT8EDkgcQ",
"alg": "RS256"
},
{
"kty": "RSA",
"use": "sig",
"kid": "LS-EQOr-3BkalkkUVh8q7Q",
"e": "AQAB",
"n": "08BLLaTz4JrTYmE4bZ9c7oKVrZKLy3KfGT5mmnslhl41nk_EV_8OUdL8wMXunC2KERdnsy5XYk4aw3LlvxZDIvjxO9PEblPsoap-WErdi9GVyAv-NJ6eJQy3S7FRSkvzQYBsLnCKm5wu0kjdQBVUCFJ7wfiZ9ayY7pH7K10qN2Utvt-qsCLUy0cJ0StuP_rquefp7_XhUw3A8IIA8P6DjfZIbpwrVjOeVWoI_ZKIwfxShghOAKBDLyQuC2PhozsqZ7HvGEeAPm06YPMWQVbE9_LBn2j_Ul_VBUWc9KfBNOzk_BMQHyF2NUlwMtqMUEcwK_hpjEeo62O_aFT8EDkgcQ",
"alg": "RS256"
}
]
}
源碼解析
介面地址都在Constants.cs這個文件,ProtocalRoutePaths這個類裡面定義的。現在知道為什麼介面地址是.well-known/openid-configuration這樣奇怪的一個路由了,這是oidc協議定的(對,都是產品的鍋)。
oidc服務配置信息介面 - DiscoveryEndpoint
代碼很長,但是邏輯很簡單,就是組裝協議規定的所有地址和信息。
需要註意的支持的claims、支持的scope等信息是遍歷所有IdentityResource、ApiResource動態獲取的。
基本上每個介面都可以配置是否顯示在元數據文檔中。
public async Task<IEndpointResult> ProcessAsync(HttpContext context)
{
_logger.LogTrace("Processing discovery request.");
// validate HTTP
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();
// generate response
_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);
}
/// <summary>
/// Creates the discovery document.
/// </summary>
/// <param name="baseUrl">The base URL.</param>
/// <param name="issuerUri">The issuer URI.</param>
public virtual async Task<Dictionary<string, object>> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri)
{
var entries = new Dictionary<string, object>
{
{ OidcConstants.Discovery.Issuer, issuerUri }
};
// jwks
if (Options.Discovery.ShowKeySet)
{
if ((await Keys.GetValidationKeysAsync()).Any())
{
entries.Add(OidcConstants.Discovery.JwksUri, baseUrl + Constants.ProtocolRoutePaths.DiscoveryWebKeys);
}
}
// endpoints
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);
}
}
}
// logout
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);
}
// scopes and claims
if (Options.Discovery.ShowIdentityScopes ||
Options.Discovery.ShowApiScopes ||
Options.Discovery.ShowClaims)
{
var resources = await ResourceStore.GetAllEnabledResourcesAsync();
var scopes = new List<string>();
// scopes
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());
}
// claims
if (Options.Discovery.ShowClaims)
{
var claims = new List<string>();
// add non-hidden identity scopes related claims
claims.AddRange(resources.IdentityResources.Where(x => x.ShowInDiscoveryDocument).SelectMany(x => x.UserClaims));
// add non-hidden api scopes related claims
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());
}
}
// grant types
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());
}
// response types
if (Options.Discovery.ShowResponseTypes)
{
entries.Add(OidcConstants.Discovery.ResponseTypesSupported, Constants.SupportedResponseTypes.ToArray());
}
// response modes
if (Options.Discovery.ShowResponseModes)
{
entries.Add(OidcConstants.Discovery.ResponseModesSupported, Constants.SupportedResponseModes.ToArray());
}
// misc
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);
}
// custom entries
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去動態返回的。
public virtual async Task<IEnumerable<Models.JsonWebKey>> CreateJwkDocumentAsync()
{
var webKeys = new List<Models.JsonWebKey>();
foreach (var key in await Keys.GetValidationKeysAsync())
{
if (key.Key is X509SecurityKey x509Key)
{
var cert64 = Convert.ToBase64String(x509Key.Certificate.RawData);
var thumbprint = Base64Url.Encode(x509Key.Certificate.GetCertHash());
if (x509Key.PublicKey is RSA rsa)
{
var parameters = rsa.ExportParameters(false);
var exponent = Base64Url.Encode(parameters.Exponent);
var modulus = Base64Url.Encode(parameters.Modulus);
var rsaJsonWebKey = new Models.JsonWebKey
{
kty = "RSA",
use = "sig",
kid = x509Key.KeyId,
x5t = thumbprint,
e = exponent,
n = modulus,
x5c = new[] { cert64 },
alg = key.SigningAlgorithm
};
webKeys.Add(rsaJsonWebKey);
}
else if (x509Key.PublicKey is ECDsa ecdsa)
{
var parameters = ecdsa.ExportParameters(false);
var x = Base64Url.Encode(parameters.Q.X);
var y = Base64Url.Encode(parameters.Q.Y);
var ecdsaJsonWebKey = new Models.JsonWebKey
{
kty = "EC",
use = "sig",
kid = x509Key.KeyId,
x5t = thumbprint,
x = x,
y = y,
crv = CryptoHelper.GetCrvValueFromCurve(parameters.Curve),
x5c = new[] { cert64 },
alg = key.SigningAlgorithm
};
webKeys.Add(ecdsaJsonWebKey);
}
else
{
throw new InvalidOperationException($"key type: {x509Key.PublicKey.GetType().Name} not supported.");
}
}
else if (key.Key is RsaSecurityKey rsaKey)
{
var parameters = rsaKey.Rsa?.ExportParameters(false) ?? rsaKey.Parameters;
var exponent = Base64Url.Encode(parameters.Exponent);
var modulus = Base64Url.Encode(parameters.Modulus);
var webKey = new Models.JsonWebKey
{
kty = "RSA",
use = "sig",
kid = rsaKey.KeyId,
e = exponent,
n = modulus,
alg = key.SigningAlgorithm
};
webKeys.Add(webKey);
}
else if (key.Key is ECDsaSecurityKey ecdsaKey)
{
var parameters = ecdsaKey.ECDsa.ExportParameters(false);
var x = Base64Url.Encode(parameters.Q.X);
var y = Base64Url.Encode(parameters.Q.Y);
var ecdsaJsonWebKey = new Models.JsonWebKey
{
kty = "EC",
use = "sig",
kid = ecdsaKey.KeyId,
x = x,
y = y,
crv = CryptoHelper.GetCrvValueFromCurve(parameters.Curve),
alg = key.SigningAlgorithm
};
webKeys.Add(ecdsaJsonWebKey);
}
else if (key.Key is JsonWebKey jsonWebKey)
{
var webKey = new Models.JsonWebKey
{
kty = jsonWebKey.Kty,
use = jsonWebKey.Use ?? "sig",
kid = jsonWebKey.Kid,
x5t = jsonWebKey.X5t,
e = jsonWebKey.E,
n = jsonWebKey.N,
x5c = jsonWebKey.X5c?.Count == 0 ? null : jsonWebKey.X5c.ToArray(),
alg = jsonWebKey.Alg,
x = jsonWebKey.X,
y = jsonWebKey.Y
};
webKeys.Add(webKey);
}
}
return webKeys;
}
結語
這一節還是比較好理解的。總而言之就是oidc協議規定了,需要提供GET介面,返回所有介面的地址,以及相關配置信息。idsv4的實現方式就是介面地址根據協議規定的去拼接,其他配置項信息根據開發的配置去動態獲取,然後以協議約定的JSON格式返回。