CrazyIter_Bin 1 jaar geleden
bovenliggende
commit
1aff11a76d

+ 3 - 3
TEAMModelBI/TEAMModelBI.csproj

@@ -65,9 +65,9 @@
 		<SpaRoot>ClientApp\</SpaRoot>
 		<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
 		<UserSecretsId>078b5d89-7d90-4f6a-88fc-7d96025990a8</UserSecretsId>
-		<Version>5.2401.24</Version>
-		<AssemblyVersion>5.2401.24.1</AssemblyVersion>
-		<FileVersion>5.2401.24.1</FileVersion>
+		<Version>5.2401.31</Version>
+		<AssemblyVersion>5.2401.31.1</AssemblyVersion>
+		<FileVersion>5.2401.31.1</FileVersion>
 		<Description>TEAMModelBI(BI)</Description>
 		<PackageReleaseNotes>BI版本说明版本切换标记2022000908</PackageReleaseNotes>
 		<PackageId>TEAMModelBI</PackageId>

+ 3 - 3
TEAMModelOS.FunctionV4/TEAMModelOS.FunctionV4.csproj

@@ -5,9 +5,9 @@
 		<OutputType>Exe</OutputType>
 		<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
 		<SignAssembly>true</SignAssembly>
-		<Version>5.2401.24</Version>
-		<AssemblyVersion>5.2401.24.1</AssemblyVersion>
-		<FileVersion>5.2401.24.1</FileVersion>
+		<Version>5.2401.31</Version>
+		<AssemblyVersion>5.2401.31.1</AssemblyVersion>
+		<FileVersion>5.2401.31.1</FileVersion>
 		<PackageId>TEAMModelOS.FunctionV4</PackageId>
 		<Authors>teammodel</Authors>
 		<Company>醍摩豆(成都)信息技术有限公司</Company>

+ 91 - 25
TEAMModelOS.SDK/Extension/CoreTokenExtensions.cs

@@ -13,6 +13,18 @@ using Azure.Identity;
 using System.Net.Http;
 using System.Collections.Concurrent;
 using System.Diagnostics;
+using Newtonsoft.Json;
+using System.Net;
+using Microsoft.AspNetCore.DataProtection;
+using Microsoft.Extensions.Configuration;
+using System.Configuration;
+using DocumentFormat.OpenXml.Spreadsheet;
+using System.Text.Json;
+using System.Security.Cryptography;
+using System.Reflection;
+using Microsoft.IdentityModel.Protocols.OpenIdConnect;
+using Microsoft.IdentityModel.Protocols;
+using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
 
 namespace TEAMModelOS.SDK.Extension
 {
@@ -44,10 +56,63 @@ namespace TEAMModelOS.SDK.Extension
                                                       .WithClientSecret(secret)
                                                       .WithAuthority(new Uri(sts.GetDescriptionText()))
                                                       .Build();
+
             var scope = ((STSScope)sts).GetDescriptionText();
+           
             var result = await app.AcquireTokenForClient(new[] { scope }).ExecuteAsync();
+
+
             return result;
         }
+        //https://learn.microsoft.com/zh-cn/entra/identity-platform/access-tokens   验证的相关文档
+        public static async Task<JwtSecurityToken> Validate(string jwtTokenToValidate, string location,string clientId, IConfiguration configuration)
+        {
+            var tenantId = "4807e9cf-87b8-4174-aa5b-e76497d7392b";
+            var OpenidConfiguration = Enum.Parse<STSOpenidConfiguration>(location, true);
+            var openIdConnectWellKnownConfigUri = new Uri(OpenidConfiguration.GetDescriptionText());
+
+            //With the Input token to be validated...
+
+            //With the above information we can validate all key aspects of the Jwt Token...
+            try
+            {
+                var openIdConfigManager = new ConfigurationManager<OpenIdConnectConfiguration>(
+                    openIdConnectWellKnownConfigUri.ToString(),
+                    new OpenIdConnectConfigurationRetriever()
+                );
+
+                OpenIdConnectConfiguration openIdConfig = await openIdConfigManager.GetConfigurationAsync().ConfigureAwait(false);
+                TokenValidationParameters validationParams = new TokenValidationParameters
+                {
+                    ValidateIssuerSigningKey = true,
+                    ValidateAudience = true,
+                    ValidateIssuer = true,
+                    ValidateLifetime = false,
+                    ValidateTokenReplay = true,
+                    RequireExpirationTime = true,
+                    RequireAudience= true,
+                    RequireSignedTokens= true,
+                    //Valid values for Validation of the JWT...
+                    ValidAudience =  configuration.GetValue<string>("Option:Audience"),
+                    ValidIssuer = openIdConfig.Issuer.Replace("{tenantid}", tenantId),
+                    //Set the Azure AD SigningKeys for Validation!
+                    IssuerSigningKeys = openIdConfig.SigningKeys,
+                };
+
+                var jwtTokenHandler = new JwtSecurityTokenHandler();
+                jwtTokenHandler.ValidateToken(jwtTokenToValidate, validationParams, out SecurityToken validToken);
+
+                return validToken as JwtSecurityToken
+                    ?? throw new SecurityTokenValidationException("Unexpected failure while parsing and validating the the JWT token specified.");
+            }
+            catch (Exception exc)
+            {
+                //Handle the Token Validation Exception (one of many types may occur)...
+
+                return null; 
+            }
+        }
+
 
         /// <summary>
         /// 驗證是否為公司Azure發行金鑰,支援大陸國際
@@ -69,31 +134,6 @@ namespace TEAMModelOS.SDK.Extension
                 return false;
             }
         }
-
-        public static bool ValidateIdToken(string token, string salt)
-        {
-            try
-            {
-                var handler = new JwtSecurityTokenHandler();
-                var validationParameters = new TokenValidationParameters
-                {
-                    RequireExpirationTime = true,
-                    ValidateIssuer = false,
-                    ValidateAudience = false,
-                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(salt)),
-                    ValidateLifetime = false,
-                    //LifetimeValidator = LifetimeValidator,
-                    ClockSkew = TimeSpan.Zero                    
-                };
-                ClaimsPrincipal principal = handler.ValidateToken(token, validationParameters, out SecurityToken securityToken);
-                return true;
-            }
-            catch(Exception ex)
-            {
-                Trace.WriteLine(ex.Message);
-                return false;
-            }
-        }
         #endregion
 
         private static async ValueTask<KeyVaultSecret> GetClientIDSecret(string clientID, string location)
@@ -167,5 +207,31 @@ namespace TEAMModelOS.SDK.Extension
             [Description("73a2bcc5-fe99-4566-aa8a-07e7bb287df1,8768b06f-c5c5-4b0c-abfb-d7ded354626d,7=O./yws0L89WcEsece:9/4deJHP4E=F,https://login.microsoftonline.com/")]
             Global
         }
+        private enum STSJwtKeys
+        {
+            [Description("https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/discovery/v2.0/keys")]
+            China,
+            [Description("https://login.microsoftonline.com/73a2bcc5-fe99-4566-aa8a-07e7bb287df1/discovery/v2.0/keys")]
+            Global
+        }
+        private enum STSOpenidConfiguration {
+            [Description("https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0/.well-known/openid-configuration")]
+            China,
+            [Description("https://login.microsoftonline.com/73a2bcc5-fe99-4566-aa8a-07e7bb287df1/v2.0/.well-known/openid-configuration")]
+            Global
+        }
+        public class MSADJwtKeys { 
+            
+            public string kty { get;set; }
+            public string use { get; set; }
+
+            public string kid { get; set; }
+            public string x5t { get; set; }
+            public string n { get; set; }
+            public string e { get; set; }
+            public List<string> x5c { get; set; }
+            public string issuer { get; set; }
+
+        }
     }
 }

+ 3 - 3
TEAMModelOS.SDK/TEAMModelOS.SDK.csproj

@@ -2,9 +2,9 @@
 
   <PropertyGroup>
     <TargetFramework>net6.0</TargetFramework>
-    <Version>5.2401.24</Version>
-    <AssemblyVersion>5.2401.24.1</AssemblyVersion>
-    <FileVersion>5.2401.24.1</FileVersion>
+    <Version>5.2401.31</Version>
+    <AssemblyVersion>5.2401.31.1</AssemblyVersion>
+    <FileVersion>5.2401.31.1</FileVersion>
     <PackageReleaseNotes>发版</PackageReleaseNotes>
   </PropertyGroup>
 

+ 32 - 2
TEAMModelOS/Controllers/Client/HiTAControlller.cs

@@ -1,3 +1,4 @@
+using Azure.Core;
 using Azure.Cosmos;
 using Azure.Storage.Blobs.Models;
 using DocumentFormat.OpenXml.Office2010.Excel;
@@ -5,6 +6,7 @@ using DocumentFormat.OpenXml.Spreadsheet;
 using DocumentFormat.OpenXml.Wordprocessing;
 using HTEXLib.COMM.Helpers;
 using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.DataProtection;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
@@ -20,8 +22,10 @@ using System.ComponentModel.DataAnnotations;
 using System.Dynamic;
 using System.IdentityModel.Tokens.Jwt;
 using System.Linq;
+using System.Net.Http;
 using System.Text.Json;
 using System.Threading.Tasks;
+using TEAMModelOS.Filter;
 using TEAMModelOS.Models;
 using TEAMModelOS.SDK;
 using TEAMModelOS.SDK.DI;
@@ -50,6 +54,7 @@ namespace TEAMModelOS.Controllers.Client
         private readonly HttpTrigger _httpTrigger;
         private readonly CoreAPIHttpService _coreAPIHttpService;
         private readonly IWebHostEnvironment _environment;
+        public readonly IHttpClientFactory _httpClientFactory;
         public HiTAControlller(IWebHostEnvironment environment,
         CoreAPIHttpService coreAPIHttpService,
             AzureStorageFactory azureStorage,
@@ -57,7 +62,7 @@ namespace TEAMModelOS.Controllers.Client
             AzureCosmosFactory azureCosmos,
             DingDing dingDing,
             SnowflakeId snowflakeId,
-            IOptionsSnapshot<Option> option, IConfiguration configuration,   IPSearcher searcher, HttpTrigger httpTrigger)
+            IOptionsSnapshot<Option> option, IConfiguration configuration,   IPSearcher searcher, HttpTrigger httpTrigger, IHttpClientFactory httpClientFactory)
         {
             _azureStorage = azureStorage;
             _azureRedis = azureRedis;
@@ -69,7 +74,7 @@ namespace TEAMModelOS.Controllers.Client
             _searcher = searcher;
             _httpTrigger = httpTrigger;
             _coreAPIHttpService = coreAPIHttpService;
-            _environment = environment;
+            _environment = environment; _httpClientFactory = httpClientFactory;
         }
 
         public class HiTAJoinSchool
@@ -160,6 +165,31 @@ namespace TEAMModelOS.Controllers.Client
             }
             return Ok(new { code=1});
         }
+        [ProducesDefaultResponseType]
+        [HttpPost("refresh-accessToken")]
+        [AuthToken(Roles = "teacher,admin")]
+        public async Task<IActionResult> RefreshAccessToken(JsonElement json) {
+            if (!json.TryGetProperty("refresh-token", out JsonElement _Authorization))
+            {
+                return BadRequest(json);
+            }
+            var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
+            var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
+
+
+            var authorizationJwt = new JwtSecurityToken(_Authorization.GetString());
+            if (authorizationJwt.Payload.Azp.Equals(clientID))
+            {
+                JwtSecurityToken securityToken = await CoreTokenExtensions.Validate($"{_Authorization}", _option.Location.Replace("-Dep", "").Replace("-Test", ""), clientID, _configuration);
+                if (securityToken!=null)
+                {
+                    var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, _option.Location.Replace("-Dep", "").Replace("-Test", ""));
+                    return Ok(new { access_token = token.AccessToken, token_type = token.TokenType, expires_in = token.ExpiresOn });
+                }
+            }
+            return Ok();
+        }
+
         [ProducesDefaultResponseType]
         [HttpGet("get-school-data")]
         public async Task<IActionResult> GetSchoolData([FromQuery] HiTAJoinSchool join)

+ 4 - 4
TEAMModelOS/TEAMModelOS.csproj

@@ -75,11 +75,11 @@
     <SpaRoot>ClientApp\</SpaRoot>
     <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
     <UserSecretsId>078b5d89-7d90-4f6a-88fc-7d96025990a8</UserSecretsId>
-    <Version>5.2401.24</Version>
-    <AssemblyVersion>5.2401.24.1</AssemblyVersion>
-    <FileVersion>5.2401.24.1</FileVersion>
+    <Version>5.2401.31</Version>
+    <AssemblyVersion>5.2401.31.1</AssemblyVersion>
+    <FileVersion>5.2401.31.1</FileVersion>
     <Description>TEAMModelOS(IES5)</Description>
-    <PackageReleaseNotes>IES版本说明版本切换标记5.2401.24.1</PackageReleaseNotes>
+    <PackageReleaseNotes>IES版本说明版本切换标记5.2401.31.1</PackageReleaseNotes>
     <PackageId>TEAMModelOS</PackageId>
     <Authors>teammodel</Authors>
     <Company>醍摩豆(成都)信息技术有限公司</Company>

+ 1 - 1
TEAMModelOS/appsettings.Development.json

@@ -18,7 +18,7 @@
     "IdTokenSalt": "8263692E2213497BB55E74792B7900B4",
     "HttpTrigger": "https://teammodelosfunction-test.chinacloudsites.cn/api/",
     //"HttpTrigger": "http://localhost:7071/api/"
-    "Version": "5.2401.24.1"
+    "Version": "5.2401.31.1"
   },
   "Azure": {
     // 测试站数据库

+ 1 - 1
TEAMModelOS/appsettings.json

@@ -18,7 +18,7 @@
     "Exp": 86400,
     "IdTokenSalt": "8263692E2213497BB55E74792B7900B4",
     "HttpTrigger": "https://teammodelosfunction.chinacloudsites.cn/api/",
-    "Version": "5.2401.24.1"
+    "Version": "5.2401.31.1"
   },
   "Azure": {
     "Storage": {