CoreTokenExtensions.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IdentityModel.Tokens.Jwt;
  5. using System.Security.Claims;
  6. using Microsoft.IdentityModel.Tokens;
  7. using Microsoft.Identity.Client;
  8. using System.ComponentModel;
  9. using System.Threading.Tasks;
  10. using Azure.Security.KeyVault.Secrets;
  11. using Azure.Identity;
  12. using System.Collections.Concurrent;
  13. using Microsoft.Extensions.Configuration;
  14. using Microsoft.IdentityModel.Protocols.OpenIdConnect;
  15. using Microsoft.IdentityModel.Protocols;
  16. namespace TEAMModelOS.SDK.Extension
  17. {
  18. public static class CoreTokenExtensions
  19. { //var issuer = Configuration.GetValue<string>("JwtSettings:Issuer");
  20. //var signKey = Configuration.GetValue<string>("JwtSettings:SignKey");
  21. private const string issuer = "account.teammodel";
  22. //Azure AD 租用戶識別碼(國際、大陸)
  23. private static List<string> tenantids = new List<string> { "73a2bcc5-fe99-4566-aa8a-07e7bb287df1", "4807e9cf-87b8-4174-aa5b-e76497d7392b" };
  24. private static ConcurrentDictionary<string, KeyVaultSecret> KeyVaultSecrets { get; } = new ConcurrentDictionary<string, KeyVaultSecret>();
  25. #region Access Token
  26. /// <summary>
  27. /// 產生AccessToken
  28. /// </summary>
  29. /// <param name="clientID"></param>
  30. /// <param name="location">服務位置,Global or China ...</param>
  31. /// <returns></returns>
  32. public static async ValueTask<AuthenticationResult> CreateAccessToken(string clientID, string clientSecret, string location)
  33. {
  34. //從金鑰庫取出秘密,此作法讓所有端直接刷新金鑰,無需傳送秘密,SPA更適用
  35. var secret = clientSecret ?? (await GetClientIDSecret(clientID, location)).Value;
  36. var sts = Enum.Parse<STSEndpoint>(location, true);
  37. IConfidentialClientApplication app;
  38. app = ConfidentialClientApplicationBuilder.Create(clientID)
  39. .WithClientSecret(secret)
  40. .WithAuthority(new Uri(sts.GetDescriptionText()))
  41. .Build();
  42. var scope = ((STSScope)sts).GetDescriptionText();
  43. var result = await app.AcquireTokenForClient(new[] { scope }).ExecuteAsync();
  44. return result;
  45. }
  46. //https://learn.microsoft.com/zh-cn/entra/identity-platform/access-tokens 验证的相关文档
  47. public static async Task<JwtSecurityToken> Validate(string jwtTokenToValidate, string location,string tenantId, IConfiguration configuration)
  48. {
  49. // var tenantId = "4807e9cf-87b8-4174-aa5b-e76497d7392b";
  50. var OpenidConfiguration = Enum.Parse<STSOpenidConfiguration>(location, true);
  51. var openIdConnectWellKnownConfigUri = new Uri(OpenidConfiguration.GetDescriptionText());
  52. //With the Input token to be validated...
  53. //With the above information we can validate all key aspects of the Jwt Token...
  54. try
  55. {
  56. var openIdConfigManager = new ConfigurationManager<OpenIdConnectConfiguration>(
  57. openIdConnectWellKnownConfigUri.ToString(),
  58. new OpenIdConnectConfigurationRetriever()
  59. );
  60. OpenIdConnectConfiguration openIdConfig = await openIdConfigManager.GetConfigurationAsync().ConfigureAwait(false);
  61. TokenValidationParameters validationParams = new TokenValidationParameters
  62. {
  63. ValidateIssuerSigningKey = true,
  64. ValidateAudience = true,
  65. ValidateIssuer = true,
  66. ValidateLifetime = false,
  67. ValidateTokenReplay = true,
  68. RequireExpirationTime = true,
  69. RequireAudience= true,
  70. RequireSignedTokens= true,
  71. //Valid values for Validation of the JWT...
  72. ValidAudience = configuration.GetValue<string>("Option:Audience"),
  73. ValidIssuer = openIdConfig.Issuer.Replace("{tenantid}", tenantId),
  74. //Set the Azure AD SigningKeys for Validation!
  75. IssuerSigningKeys = openIdConfig.SigningKeys,
  76. };
  77. var jwtTokenHandler = new JwtSecurityTokenHandler();
  78. jwtTokenHandler.ValidateToken(jwtTokenToValidate, validationParams, out SecurityToken validToken);
  79. return validToken as JwtSecurityToken
  80. ?? throw new SecurityTokenValidationException("Unexpected failure while parsing and validating the the JWT token specified.");
  81. }
  82. catch (Exception exc)
  83. {
  84. //Handle the Token Validation Exception (one of many types may occur)...
  85. return null;
  86. }
  87. }
  88. /// <summary>
  89. /// 驗證是否為公司Azure發行金鑰,支援大陸國際
  90. /// </summary>
  91. /// <param name="token"></param>
  92. /// <returns></returns>
  93. public static bool ValidateAccessToken(JwtSecurityToken token)
  94. {
  95. try
  96. {
  97. if (token.Payload.TryGetValue("tid", out var value) && value is string tokenTenantId)
  98. {
  99. return tenantids.Contains(tokenTenantId);
  100. }
  101. return false;
  102. }
  103. catch (Exception)
  104. {
  105. return false;
  106. }
  107. }
  108. #endregion
  109. private static async ValueTask<KeyVaultSecret> GetClientIDSecret(string clientID, string location)
  110. { //Azure 金鑰庫處理
  111. var s = await Task.Run(() =>
  112. {
  113. var secret = KeyVaultSecrets.GetOrAdd(clientID, (x) =>
  114. {
  115. try
  116. {
  117. var sts = Enum.Parse<CoreServiceClient>(location, true);
  118. var scrtetstring = sts.GetDescriptionText().Split(",");
  119. //TODO 之後驗證端點用KnownAuthorityHosts取代,此SDK版本無支援
  120. var secret = new ClientSecretCredential(scrtetstring[0], scrtetstring[1], scrtetstring[2], new TokenCredentialOptions() { AuthorityHost = new Uri(scrtetstring[3]) });
  121. var client = new SecretClient(new Uri(((KeyVaultEndpoint)sts).GetDescriptionText()), secret);
  122. var clientSecret = client.GetSecretAsync(clientID).ConfigureAwait(false);
  123. return clientSecret.GetAwaiter().GetResult();
  124. }
  125. catch
  126. {
  127. return null;
  128. }
  129. });
  130. return secret;
  131. });
  132. return s;
  133. }
  134. public static bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters)
  135. {
  136. return true;
  137. //if (expires != null)
  138. //{
  139. // if (DateTime.UtcNow < expires)
  140. // {
  141. // return true;
  142. // }
  143. //}
  144. //return false;
  145. }
  146. private enum STSEndpoint
  147. {
  148. [Description("https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b")]
  149. China,
  150. [Description("https://login.microsoftonline.com/73a2bcc5-fe99-4566-aa8a-07e7bb287df1")]
  151. Global
  152. }
  153. private enum STSScope
  154. {
  155. [Description("api://72643704-b2e7-4b26-b881-bd5865e7a7a5/.default")]
  156. China,
  157. [Description("api://8768b06f-c5c5-4b0c-abfb-d7ded354626d/.default")]
  158. Global
  159. }
  160. private enum KeyVaultEndpoint
  161. {
  162. [Description("https://corekeyvaultcn.vault.azure.cn/")]
  163. China,
  164. [Description("https://corekeyvaultjp.vault.azure.net/")]
  165. Global
  166. }
  167. private enum CoreServiceClient
  168. {
  169. [Description("4807e9cf-87b8-4174-aa5b-e76497d7392b,72643704-b2e7-4b26-b881-bd5865e7a7a5,tRYbDXtotEOe2Bbmo=[3h9Hbu_Trt:c6,https://login.partner.microsoftonline.cn")]
  170. China,
  171. [Description("73a2bcc5-fe99-4566-aa8a-07e7bb287df1,8768b06f-c5c5-4b0c-abfb-d7ded354626d,7=O./yws0L89WcEsece:9/4deJHP4E=F,https://login.microsoftonline.com/")]
  172. Global
  173. }
  174. private enum STSJwtKeys
  175. {
  176. [Description("https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/discovery/v2.0/keys")]
  177. China,
  178. [Description("https://login.microsoftonline.com/73a2bcc5-fe99-4566-aa8a-07e7bb287df1/discovery/v2.0/keys")]
  179. Global
  180. }
  181. private enum STSOpenidConfiguration {
  182. [Description("https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0/.well-known/openid-configuration")]
  183. China,
  184. [Description("https://login.microsoftonline.com/73a2bcc5-fe99-4566-aa8a-07e7bb287df1/v2.0/.well-known/openid-configuration")]
  185. Global
  186. }
  187. public class MSADJwtKeys {
  188. public string kty { get;set; }
  189. public string use { get; set; }
  190. public string kid { get; set; }
  191. public string x5t { get; set; }
  192. public string n { get; set; }
  193. public string e { get; set; }
  194. public List<string> x5c { get; set; }
  195. public string issuer { get; set; }
  196. }
  197. }
  198. }