網站集成Github、Gitee登錄
在現代應用開發中,第三方登錄是常見的功能,可以降低用戶登錄的門檻,所以我給我的我的網站集成 github、gitee 登錄教程,今天來看看如何在.net core 中集成 ,代碼比較簡單,以此記錄一下。
Github登錄
配置 GitHub 認證
在 GitHub 上創建一個 應用,獲取 Client ID 和 Client Secret。只需要在gitub的開發設置里面申請就好了,我覺得有的網站(包括gitee)第三方登錄申請比較友好,直接注冊,并且支持loaclhost的調試,大大的降低了難度。

頁面配置按鈕
頁面配置按鈕,點擊登錄圖標跳轉到https://gitee.com/oauth/authorize,這個地址是固定的
代碼如下
window.location. + appId;
其中appId是你申請的clientId
跳轉之后,會自動跳到你的回調頁面然后攜帶一個code,然后你拿到這個code就可以
獲取accessToken了
請求AccessToken
請求后臺接口,把code傳過去
const loading = loadService.openFullLoading('登錄認證中...');
let code = route.query.code;
let loginType = route.query.openLoginType;
let params = {
code: code,
loginType: loginType
}
openLoginApi(params).then(res => {
window.location.href = import.meta.env.VITE_WEB_UI;
loadService.closeFullLoading(loading);
})
請求accessToken的接口是https://github.com/login/oauth/access_token
代碼如下
private async Task<string> GetAccessToken(string authorizationCode, string clientId, string clientSecret)
{
if (string.IsNullOrEmpty(authorizationCode))
throw new AuthException("github認證登錄失?。篴uthorizationCode為空");
string apiUrl = $"https://github.com/login/oauth/access_token?client_id={clientId}&client_secret={clientSecret}&code={authorizationCode}";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
string response = await httpClient.GetStringAsync(apiUrl);
dynamic result = JsonConvert.DeserializeObject(response);
return result.access_token;
}
其中 httpClient.DefaultRequestHeaders.Add("Accept", "application/json")你可以根據你的要求去設置header來得到的接口數據的格式
請根據AccessToken獲取用戶信息
private async Task<GitHubUserInfo> GetGitHubUser(string accessToken)
{
string apiUrl = "https://api.github.com/user";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", "xiandan");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
string response = await httpClient.GetStringAsync(apiUrl);
dynamic result = JsonConvert.DeserializeObject(response);
GitHubUserInfo gitHubUserInfo = new GitHubUserInfo();
gitHubUserInfo.LoginName= result.login;
gitHubUserInfo.AvtarUrl= result.avatar_url;
gitHubUserInfo.OpenID = result.id;
gitHubUserInfo.OpenAuthEnum = OpenAuthEnum.GitHub;
gitHubUserInfo.Sex = "男";
return gitHubUserInfo;
}
其中httpClient.DefaultRequestHeaders.Add("User-Agent", "xiandan"),如果你不設置User-Agent的話,可能會出現接口403的情況,具體的根據自己的情況處理
保存用戶信息并且登錄
上面的方法返回了用戶信息后,既可以執行你的業務操作了,如創建用戶信息并且生成登錄token,我的代碼
public async Task<LoginUser> CreateOpenUser(BaseOpenUserInfo openUserInfo)
{
var accountRepository = unitOfWork.GetRepository<Account>();
var userRepository = unitOfWork.GetRepository<User>();
var uploadFileRepository = unitOfWork.GetRepository<UploadFile>();
Account account = await accountRepository.SelectSingleAsync(s => s.AccountName == openUserInfo.OpenID);
UploadFile avatarFile = null;
User user = null;
if (account == null)
{
RegisterUserDTO registerUserDto = CreateOpenUser(openUserInfo, ref avatarFile);
var tup = CreateAccountUser(registerUserDto);
account = tup.Item1;
user = tup.Item2;
await accountRepository.InsertAsync(account);
await userRepository.InsertAsync(user);
if (avatarFile != null)
{
avatarFile.Id = CreateEntityId();
avatarFile.UserId = user.Id;
avatarFile.EntityId = user.Id;
await uploadFileRepository.InsertAsync(avatarFile);
}
await unitOfWork.CommitAsync();
}
else
{
user = await userRepository.SelectSingleAsync(s => s.AccountId == account.Id);
avatarFile = await uploadFileRepository.SelectSingleAsync(s => s.EntityId == user.Id && s.EntityName == EntityCode.UserEntityName);
}
LoginUser loginUser = CreateLoginUser(user, account, avatarFile);
return loginUser;
}
Gitee登錄
gitee登錄基本上和github登錄差不多,也支持loaclhost的調試
window.location. + clientId + "&redirect_uri=" + redirectUri + "&response_type=code";
private async Task<string> GetAccessToken(string code)
{
string url = $"https://gitee.com/oauth/token";
HttpClient client = new HttpClient();
FormUrlEncodedContent content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type","authorization_code"),
new KeyValuePair<string, string>("code",code),
new KeyValuePair<string, string>("client_id",GiteeConfigOption.ClientId),
new KeyValuePair<string, string>("client_secret",GiteeConfigOption.ClientSecret),
new KeyValuePair<string, string>("redirect_uri",GiteeConfigOption.RedirectUri)
});
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
dynamic tokenResponse = JsonConvert.DeserializeObject(responseBody);
return tokenResponse.access_token;
}
else
{
throw new Exception($"獲取訪問令牌失敗:{response.StatusCode}");
}
}
private async Task<GiteeUserInfo> GetGiteeUserInfo(string accessToken)
{
string url ="https://gitee.com/api/v5/user?access_token="+accessToken;
HttpClient httpClient = new HttpClient();
string response=await httpClient.GetStringAsync(url);
dynamic result = JsonConvert.DeserializeObject(response);
GiteeUserInfo giteeUserInfo = new GiteeUserInfo();
giteeUserInfo.OpenAuthEnum = OpenAuthEnum.Gitee;
giteeUserInfo.OpenID = result.id;
giteeUserInfo.Name= result.name;
giteeUserInfo.AvatarUrl = result.avatar_url;
giteeUserInfo.Sex = "男";
return giteeUserInfo;
}
這樣,基本的.net core 集成 GitHub、gitee 登錄就完成了。
作者:程序員奶牛
個人開源網站:https://www.xiandanplay.com
源碼地址:https://gitee.com/MrHanchichi/xian-dan

浙公網安備 33010602011771號