feat:统一登录集成完成

develop
old易 2023-11-09 15:21:18 +08:00
parent ab7712e22f
commit ec0d77918d
6 changed files with 227 additions and 61 deletions

View File

@ -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<MessageModel<bool>> DataSync([FromBody] object obj)
{
string newobj = obj.ToString().Replace("object", "_object");
// CasdoorHookModel
return new MessageModel<bool>()
{
};
}
/// <summary>
///Oauth2验证回调
@ -32,32 +51,50 @@ namespace New_College.Controllers
/// <returns></returns>
[HttpGet]
[Route("callback")]
public async Task<MessageModel<string>> Callback(string code, string state)
public async Task<MessageModel<CasDoorToken>> Callback(string code, string state, string scope)
{
var response = new CasDoorToken();
string jwtStr = string.Empty;
bool suc = false;
var getaccesstoken = CasdoorHttpHelper.Http_Post<CasdoorGetTokenResponse>("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<string, string>
{
{ "Authorization", string.Format("Bearer {0}", getaccesstoken.access_token) }
};
if (getaccesstoken.access_token == null)
{
return new MessageModel<CasDoorToken>()
{
msg = "code已失效",
success = false
};
}
response.servicetoken = getaccesstoken.access_token;
var userinfo = CasdoorHttpHelper.Http_Get<CasdoorUserInfoDto>("/api/userinfo", headers, new Dictionary<string, string>());
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<CasDoorToken>()
{
success = false
var gettoken = CasdoorHttpHelper.Post_AccessToken<CasdoorGetTokenResponse>(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<string>()
};
}
}
return new MessageModel<CasDoorToken>()
{
success = suc,
msg = suc ? "success" : "fail",
response = jwtStr
response = response
};
}

View File

@ -1144,7 +1144,7 @@
</summary>
<returns></returns>
</member>
<member name="M:New_College.Controllers.OauthController.Callback(System.String,System.String)">
<member name="M:New_College.Controllers.OauthController.Callback(System.String,System.String,System.String)">
<summary>
Oauth2验证回调
</summary>

View File

@ -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
}

View File

@ -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
{
/// <summary>
/// 获取accesstoken
/// post 统一请求接口
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="code"></param>
/// <param name="inter"></param>
/// <param name="content"></param>
/// <returns></returns>
public static T Post_AccessToken<T>(string code) where T : new()
public static T Http_Post<T>(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<T>(responseStr);
return obj;
@ -40,28 +44,48 @@ namespace New_College.Common
}
/// <summary>
/// 刷新token
///泛型GET
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="refresh_token"></param>
/// <param name="scope"></param>
/// <param name="inter"></param>
/// <param name="param"></param>
/// <returns></returns>
public static T Post_RefreshToken<T>(string refresh_token, string scope) where T : new()
public static T Http_Get<T>(string inter, Dictionary<string, string> headers, Dictionary<string,string> 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<T>(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; }
}
}

View File

@ -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; }
}
}

View File

@ -48,6 +48,8 @@ namespace New_College.FrameWork.Services
}
/// <summary>
///
/// </summary>