From ec0d77918d0e96ecf3edc353b4187686a09f158b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?old=E6=98=93?= <156663459@qq.com> Date: Thu, 9 Nov 2023 15:21:18 +0800 Subject: [PATCH] =?UTF-8?q?feat=EF=BC=9A=E7=BB=9F=E4=B8=80=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E9=9B=86=E6=88=90=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/OAuthController.cs | 81 ++++++++---- New_College.Api/New_College.xml | 2 +- New_College.Api/appsettings.json | 4 +- .../Helper/CasdoorHttpHelper.cs | 79 ++++++------ .../ViewModels/Result/CasDoorTokenResult.cs | 120 ++++++++++++++++++ New_College.Services/sysUserInfoServices.cs | 2 + 6 files changed, 227 insertions(+), 61 deletions(-) diff --git a/New_College.Api/Controllers/OAuthController.cs b/New_College.Api/Controllers/OAuthController.cs index 58f974f..f3d218e 100644 --- a/New_College.Api/Controllers/OAuthController.cs +++ b/New_College.Api/Controllers/OAuthController.cs @@ -3,9 +3,14 @@ using Microsoft.AspNetCore.Mvc; using New_College.AuthHelper.OverWrite; using New_College.Common; using New_College.Common.Helper; +using New_College.IServices; using New_College.Model; using New_College.Model.ViewModels; using NPOI.SS.Formula.Functions; +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using System.Text.Json; using System.Threading.Tasks; namespace New_College.Controllers @@ -15,15 +20,29 @@ namespace New_College.Controllers [Route("api/oauth")] public class OauthController : Controller { - - public OauthController() + readonly IV_CustomerInfoServices _CustomerInfoServices; + public OauthController(IV_CustomerInfoServices v_CustomerInfoServices) { - + _CustomerInfoServices = v_CustomerInfoServices; } + [HttpPost] + [Route("sync")] + public async Task> DataSync([FromBody] object obj) + { + string newobj = obj.ToString().Replace("object", "_object"); + // CasdoorHookModel + + + return new MessageModel() + { + + }; + } + /// ///Oauth2验证回调 @@ -32,32 +51,50 @@ namespace New_College.Controllers /// [HttpGet] [Route("callback")] - public async Task> Callback(string code, string state) + public async Task> Callback(string code, string state, string scope) { + var response = new CasDoorToken(); string jwtStr = string.Empty; bool suc = false; + var getaccesstoken = CasdoorHttpHelper.Http_Post("api/login/oauth/access_token", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRequest() { code = code, grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json"));//获取access_token + var headers = new System.Collections.Generic.Dictionary + { + { "Authorization", string.Format("Bearer {0}", getaccesstoken.access_token) } + }; + if (getaccesstoken.access_token == null) + { + return new MessageModel() + { + msg = "code已失效", + success = false + }; + } + response.servicetoken = getaccesstoken.access_token; + var userinfo = CasdoorHttpHelper.Http_Get("/api/userinfo", headers, new Dictionary()); + var user = await _CustomerInfoServices.GetUserInfo(new Model.Request.LoginQuery() { openId = userinfo.sub }); + if (user != null) + { + if (user.Item1) + { + TokenModelJwt tokenModel = new TokenModelJwt { Uid = user.Item2.Id, Role = "users" }; + jwtStr = JwtHelper.IssueJwt(tokenModel); + response.token = jwtStr; + suc = true; + } + else + { + return new MessageModel() + { + success = false - var gettoken = CasdoorHttpHelper.Post_AccessToken(code); - //var user = await _sysUserInfoServices.GetUserRoleNameStr(name, MD5Helper.MD5Encrypt32(pass)); - //if (user != null) - //{ - - TokenModelJwt tokenModel = new TokenModelJwt { Uid = 1, Role = gettoken.access_token }; - - jwtStr = JwtHelper.IssueJwt(tokenModel); - suc = true; - //} - //else - //{ - // jwtStr = "login fail!!!"; - //} - - - return new MessageModel() + }; + } + } + return new MessageModel() { success = suc, msg = suc ? "success" : "fail", - response = jwtStr + response = response }; } diff --git a/New_College.Api/New_College.xml b/New_College.Api/New_College.xml index b1269cf..8dd3569 100644 --- a/New_College.Api/New_College.xml +++ b/New_College.Api/New_College.xml @@ -1144,7 +1144,7 @@ - + Oauth2验证回调 diff --git a/New_College.Api/appsettings.json b/New_College.Api/appsettings.json index f763510..37c2ef4 100644 --- a/New_College.Api/appsettings.json +++ b/New_College.Api/appsettings.json @@ -212,8 +212,8 @@ "OrganizationName": "六纬生涯", "ApplicationName": "六纬生涯", "ApplicationType": "webapi", - "ClientId": "ae6bdccc3a7821232b31", - "ClientSecret": "ac4f5eeb78528f2b89d56d2c3148d717c5db5e99", + "ClientId": "776d639918192c449537", + "ClientSecret": "d556f0692052a2df56614282dd86895b04783262", "CallbackPath": "http://192.168.103.119:8000/login/oauth/authorize?client_id=ae6bdccc3a7821232b31&response_type=code&redirect_uri=http://192.168.103.100:8083/callback&scope=read&state=casdoor", "RequireHttpsMetadata": false } diff --git a/New_College.Common/Helper/CasdoorHttpHelper.cs b/New_College.Common/Helper/CasdoorHttpHelper.cs index e0ad695..705b244 100644 --- a/New_College.Common/Helper/CasdoorHttpHelper.cs +++ b/New_College.Common/Helper/CasdoorHttpHelper.cs @@ -1,7 +1,9 @@ using Newtonsoft.Json; using System; using System.Collections.Generic; +using System.Linq; using System.Net.Http; +using System.Security.Policy; using System.Text; namespace New_College.Common @@ -9,25 +11,27 @@ namespace New_College.Common public class CasdoorHttpHelper { + /// - /// 获取accesstoken + /// post 统一请求接口 /// /// - /// + /// + /// /// - public static T Post_AccessToken(string code) where T : new() + public static T Http_Post(string inter, HttpContent content) where T : new() { var authinfo = new T(); try { - string requestUri = string.Format("{0}/api/login/oauth/access_token", CasdoorConfig.Endpoint); + string requestUri = string.Format("{0}/{1}", CasdoorConfig.Endpoint, inter); var httpClientHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true }; using (HttpClient httpClient = new HttpClient(httpClientHandler)) { - var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRequest() { code = code, grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json"); + // var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRefeshToken() { refresh_token = refresh_token, scope = "built-in", grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json"); var responseStr = httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result; var obj = JsonConvert.DeserializeObject(responseStr); return obj; @@ -40,28 +44,48 @@ namespace New_College.Common } - /// - /// 刷新token + ///泛型GET /// /// - /// - /// + /// + /// /// - public static T Post_RefreshToken(string refresh_token, string scope) where T : new() + public static T Http_Get(string inter, Dictionary headers, Dictionary dic) where T : new() { + var authinfo = new T(); try { - string requestUri = string.Format("{0}/api/login/oauth/refresh_token", CasdoorConfig.Endpoint); - var httpClientHandler = new HttpClientHandler + string result = ""; + StringBuilder builder = new StringBuilder(); + builder.Append(CasdoorConfig.Endpoint); + builder.Append(inter); + if (dic.Count > 0) { - ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true + builder.Append("?"); + int i = 0; + foreach (var item in dic) + { + if (i > 0) + builder.Append("&"); + builder.AppendFormat("{0}={1}", item.Key, item.Value); + i++; + } + + } + var httpClientHandler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true, }; using (HttpClient httpClient = new HttpClient(httpClientHandler)) { - var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRefeshToken() { refresh_token = refresh_token, scope = "built-in", grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json"); - var responseStr = httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result; + httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); + if (headers.Any()) + { + httpClient.DefaultRequestHeaders.Add(headers.FirstOrDefault().Key, headers.FirstOrDefault().Value); + } + var responseStr = httpClient.GetAsync(builder.ToString()).Result.Content.ReadAsStringAsync().Result; var obj = JsonConvert.DeserializeObject(responseStr); return obj; } @@ -70,32 +94,15 @@ namespace New_College.Common { throw ex; } + + + + } - private class CasdoorRequest - { - public string grant_type { get; set; } - public string client_id { get; set; } - public string client_secret { get; set; } - public string code { get; set; } - } - - - - private class CasdoorRefeshToken - { - - public string grant_type { get; set; } - public string client_id { get; set; } - public string client_secret { get; set; } - public string scope { get; set; } - - public string refresh_token { get; set; } - - } } diff --git a/New_College.Model/ViewModels/Result/CasDoorTokenResult.cs b/New_College.Model/ViewModels/Result/CasDoorTokenResult.cs index 28abe1c..10e1f8c 100644 --- a/New_College.Model/ViewModels/Result/CasDoorTokenResult.cs +++ b/New_College.Model/ViewModels/Result/CasDoorTokenResult.cs @@ -16,4 +16,124 @@ namespace New_College.Model.ViewModels public string error_description { get; set; } } + + + public class CasdoorRequest + { + public string grant_type { get; set; } + public string client_id { get; set; } + public string client_secret { get; set; } + public string code { get; set; } + } + + + + public class CasdoorRefeshToken + { + + public string grant_type { get; set; } + public string client_id { get; set; } + public string client_secret { get; set; } + public string scope { get; set; } + + public string refresh_token { get; set; } + + } + + public class CasdoorUserInfoDto + { + public string address { get; set; } + public string aud { get; set; } + public string email { get; set; } + public string[] groups { get; set; } + public string iss { get; set; } + public string name { get; set; } + public string phone { get; set; } + public string picture { get; set; } + public string preferred_username { get; set; } + public string sub { get; set; } + } + + + + + public class CasdoorHookModel + { + public int id { get; set; } + public string owner { get; set; } + public string name { get; set; } + public DateTime createdTime { get; set; } + public string organization { get; set; } + public string clientIp { get; set; } + public string user { get; set; } + public string method { get; set; } + public string requestUri { get; set; } + public string action { get; set; } + public bool isTriggered { get; set; } + public string _object { get; set; } + public Extendeduser extendedUser { get; set; } + } + + public class Extendeduser + { + public string owner { get; set; } + public string name { get; set; } + public DateTime createdTime { get; set; } + public string updatedTime { get; set; } + public string id { get; set; } + public string type { get; set; } + public string password { get; set; } + public string passwordSalt { get; set; } + public string displayName { get; set; } + public string avatar { get; set; } + public string permanentAvatar { get; set; } + public string email { get; set; } + public string phone { get; set; } + public string location { get; set; } + public object address { get; set; } + public string affiliation { get; set; } + public string title { get; set; } + public int score { get; set; } + public int ranking { get; set; } + public bool isOnline { get; set; } + public bool isAdmin { get; set; } + public bool isForbidden { get; set; } + public bool isDeleted { get; set; } + public string signupApplication { get; set; } + public Properties properties { get; set; } + } + + public class Properties + { + public string bio { get; set; } + public string checkinDate { get; set; } + public string editorType { get; set; } + public DateTime emailVerifiedTime { get; set; } + public string fileQuota { get; set; } + public string location { get; set; } + public string no { get; set; } + public string oauth_QQ_displayName { get; set; } + public string oauth_QQ_verifiedTime { get; set; } + public string oauth_WeChat_displayName { get; set; } + public string oauth_WeChat_verifiedTime { get; set; } + public string onlineStatus { get; set; } + public string phoneVerifiedTime { get; set; } + public string renameQuota { get; set; } + public string tagline { get; set; } + public string website { get; set; } + } + + + + public class CasDoorToken + { + + public string token { get; set; } + + public string servicetoken { get; set; } + + + } + + } diff --git a/New_College.Services/sysUserInfoServices.cs b/New_College.Services/sysUserInfoServices.cs index 15c2013..c5f4212 100644 --- a/New_College.Services/sysUserInfoServices.cs +++ b/New_College.Services/sysUserInfoServices.cs @@ -48,6 +48,8 @@ namespace New_College.FrameWork.Services } + + /// /// ///