CoreTokenExtensions.cs 9.8 KB

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