
新年新氣象,趁著新年的喜慶,肝了十來天,終于發了第一版,希望大家喜歡,
如果有不喜歡看文字的童鞋,可以直接看下面的地址體驗一下:
https://oauthlogin.net/
前言
此次帶來得這個小專案是 OAuth2 登錄組件,看到 Java 平臺 JustAuth 專案很方便的接入第三方平臺登錄,心里癢癢啊,搜了一大圈,發現我大 .netcore 能用的可說是少之又少,而且代碼寫得一塌糊涂,全在一個庫里,代碼風格也看不慣,所以下定決定,操起鍵盤,開干,
關于 OAuth2 的一些基礎、原理介紹文章太多了,寫的好的不在少數,在頁尾我提供了幾個鏈接,喜歡的朋友看一下,這里就不深入解釋,直入主題,
如何使用
這里拿接入 github 登錄做演示,新建 Asp.NET Core Web應用程式 專案,名叫 GithubLogin(PS:你可以自己起個更牛×的名字),選擇模型視圖控制器這個,當然你可以選擇其他的,
第一步:安裝
安裝這個 nuget 包:
Install-Package MrHuo.OAuth.Github -Version 1.0.0
第二步:配置
打開 appsettings.json 寫入下面的配置:
{
"oauth": {
"github": {
"app_id": "github_app_id",
"app_key": "github_app_key",
"redirect_uri": "https://oauthlogin.net/oauth/githubcallback",
"scope": "repo"
}
}
}
這里的配置可以通過 https://github.com/settings/applications/new 來注冊,redirect_uri 可以填寫本地 localhost 地址的,超級方便,這也是為什么使用 github 登錄做演示的原因,

創建完成后,在這個界面里生成 client secret:

輸入密碼,生成成功后是這樣的:

把界面里的 Client ID,Client secret,連同上一個界面里填寫的 Authorization callback URL 全部填寫到組態檔對應位置,現在組態檔 appsettings.json 是這樣的:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"oauth": {
"github": {
"app_id": "c95fxxxxxx0d09",
"app_key": "c6a73xxxxxx6375",
"redirect_uri": "http://localhost:5000/oauth/githubcallback",
"scope": "repo"
}
}
}
下面的
scope暫且不管他,你想深入了解它的作用的話,后面再說,
第三步:寫代碼
在 Startup.cs 檔案中注入組件:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton(new GithubOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:github")));
}
檔案中其他代碼沒有修改,只加了這一行而已,
新建一個 OAuthController 類,代碼如下:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MrHuo.OAuth.Github;
namespace GithubLogin.Controllers
{
public class OAuthController: Controller
{
[HttpGet("oauth/github")]
public IActionResult Github([FromServices] GithubOAuth githubOAuth)
{
return Redirect(githubOAuth.GetAuthorizeUrl());
}
[HttpGet("oauth/githubcallback")]
public async Task<IActionResult> GithubCallback(
[FromServices] GithubOAuth githubOAuth,
[FromQuery] string code)
{
return Json(await githubOAuth.AuthorizeCallback(code));
}
}
}
你沒看錯,就這點代碼就好了,我們來運行一下試試:

專案運行之后,在地址欄里輸入下面這個地址:http://localhost:5000/oauth/github,因為我們沒有修改任何代碼,沒有在視圖上做任何鏈接,所以就勞煩手動啦~~
回車之后,順利跳轉到 github 授權:

點擊綠色的 Authorize 按鈕之后稍等片刻,你會看到下面這個結果:

順利拿到了用戶資訊(PS:請忽略我少的可憐的粉絲,曾經我不強求 --ToT)

好了,到這里我的表演結束了,可以看到接入流程非常流程,卡人主要是在申請這些步驟,下面講講原理之類的,隨便說一些...如果覺得我啰嗦,那么就不用往下看了,因為下面我會更啰嗦,
當然,除了 github 現在已經接入了12個平臺,其中 QQ 和抖音我沒有注冊到應用,無法測驗,所以暫時沒有 nuget 包,一個人的力量總是有限的,在這里我請求各位有閑時間或者有 appid 資源的大佬,為這個小專案做一些貢獻,是她走的遠一些,

更多的 nuget 包,進這里 https://www.nuget.org/profiles/mrhuo 或者在 VS nuget 包管理器里搜索 MrHuo.OAuth,就可以了,
請忽略
nuget上其他幾個垃圾包,那是很多年很多年以前寫的,舍不得刪,
開發背景
第三方平臺登錄說白了就是實作 OAuth2 協議,很多平臺比如支付寶、百度、github、微軟,甚至是抖音、快手很多平臺都提供了開放介面,但是,很多平臺會在這個標準協議的基礎上增加、修改一些東西,比如:標準協議里,獲取 authorize code 時應提供 client_id,微信公眾平臺非要把它改成 appid,再比如:獲取用戶資訊時,只需要 access_token 引數,微信公眾平臺這邊非要提供一個 openid,當然這是在所難免的,因為各個平臺實際業務還是千差萬別,無法做到完全的統一,那這就給我們開發者帶來一個困擾,開發第三方登錄時很困難,當然,開發一兩個也無所謂,要是多了呢?
假如有這么一個產品經理,他想接入很多的登錄方式,讓使用者無論使用哪種平臺,都能在這里順利登錄,找到回家的路呢(PS:產品經理你別跑,看我40米的大刀),

無疑,給我們一個考驗,如何做到一個標準化,可配置,可擴展呢?這就是一個需要深究的問題,下面我就說說我肝這個專案的一些想法,說的不好別噴我,我還年輕(PS:三十多歲老大叔別裝嫩),還要臉......

制定標準
看了很多檔案之后,我們會發現,萬變不離其宗,總有規律可循,總的來說,有下面3個步驟:
GetAuthorizeUrl
這一步通過 client_id,redirect_uri 等幾個引數來獲取授權 url,跳轉到這個 url 之后將在第三方平臺上完成登錄,完成登錄之后會跳轉到上面提供的 redirect_uri 這個地址,并且帶上一個 code 引數,
GetAccessToken
這一步里,拿到上面的 code 之后去第三方平臺換 access_token,
GetUserInfo
這一步并非必須,但是我們既然是做第三方登錄,登錄之后還是需要和自己平臺的一些業務系結用戶賬號,或者使用現有資訊注冊一個用戶,這個方法就顯得尤為重要了,
到此,就這3個步驟,我覺得時需要制定在標準里面的,所以我就寫了下面這個介面來規范它:
/// <summary>
/// OAuth 登錄 API 介面規范
/// </summary>
public interface IOAuthLoginApi<TAccessTokenModel, TUserInfoModel>
where TAccessTokenModel : IAccessTokenModel
where TUserInfoModel : IUserInfoModel
{
/// <summary>
/// 獲取跳轉授權的 URL
/// </summary>
/// <param name="state"></param>
/// <returns></returns>
string GetAuthorizeUrl(string state = "");
/// <summary>
/// 異步獲取 AccessToken
/// </summary>
/// <param name="code"></param>
/// <param name="state"></param>
/// <returns></returns>
Task<TAccessTokenModel> GetAccessTokenAsync(string code, string state = "");
/// <summary>
/// 異步獲取用戶詳細資訊
/// </summary>
/// <param name="accessTokenModel"></param>
/// <returns></returns>
Task<TUserInfoModel> GetUserInfoAsync(TAccessTokenModel accessTokenModel);
}
可以看到我將 AccessToken 和 UserInfo 做成了泛型引數,因為他們是這個規范里的可變部分,代碼中 state 引數的作用呢就是為了防止 CORS 攻擊做的防偽驗證,這里暫不做解釋,其他檔案里都有這個引數的解釋,

如何擴展新的平臺
這里拿 Gitee 來做演示:
第一步:找平臺對應 OAuth 檔案,找到獲取用戶資訊介面回傳JSON,轉換為 C# 物體類,如下:
根據自己需要和介面標準,擴展用戶屬性
public class GiteeUserModel : IUserInfoModel
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("avatar_url")]
public string Avatar { get; set; }
[JsonPropertyName("message")]
public string ErrorMessage { get; set; }
[JsonPropertyName("email")]
public string Email { get; set; }
[JsonPropertyName("blog")]
public string Blog { get; set; }
//...其他屬性類似如上
}
這里使用了
.netcore內置的Json序列化庫,據說性能提高了不少!
第二步:寫對應平臺的授權介面
/// <summary>
/// https://gitee.com/api/v5/oauth_doc#/
/// </summary>
public class GiteeOAuth : OAuthLoginBase<GiteeUserModel>
{
public GiteeOAuth(OAuthConfig oauthConfig) : base(oauthConfig) { }
protected override string AuthorizeUrl => "https://gitee.com/oauth/authorize";
protected override string AccessTokenUrl => "https://gitee.com/oauth/token";
protected override string UserInfoUrl => "https://gitee.com/api/v5/user";
}
加上注釋,總共十行,如你所見,非常方便,如果該平臺協議遵循 OAuth2 標準開發,那么就這么幾行就好了,
當然,如果不按規矩自定義欄位的平臺,也可以擴展,比如微信公眾平臺,
WechatAccessTokenModel.cs AccessToken 類擴展
namespace MrHuo.OAuth.Wechat
{
public class WechatAccessTokenModel : DefaultAccessTokenModel
{
[JsonPropertyName("openid")]
public string OpenId { get; set; }
}
}
繼承自
DefaultAccessTokenModel,新增欄位OpenId,因為獲取用戶資訊需要獲取OpenId,所以這里需要它,
WechatUserInfoModel.cs 用戶資訊類
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace MrHuo.OAuth.Wechat
{
public class WechatUserInfoModel : IUserInfoModel
{
[JsonPropertyName("nickname")]
public string Name { get; set; }
[JsonPropertyName("headimgurl")]
public string Avatar { get; set; }
[JsonPropertyName("language")]
public string Language { get; set; }
[JsonPropertyName("openid")]
public string Openid { get; set; }
[JsonPropertyName("sex")]
public int Sex { get; set; }
[JsonPropertyName("province")]
public string Province { get; set; }
[JsonPropertyName("city")]
public string City { get; set; }
[JsonPropertyName("country")]
public string Country { get; set; }
/// <summary>
/// 用戶特權資訊,json 陣列,如微信沃卡用戶為(chinaunicom)
/// </summary>
[JsonPropertyName("privilege")]
public List<string> Privilege { get; set; }
[JsonPropertyName("unionid")]
public string UnionId { get; set; }
[JsonPropertyName("errmsg")]
public string ErrorMessage { get; set; }
}
}
這里用戶資訊欄位上邊的
[JsonPropertyName("xxxx")]完全按照檔案里的欄位寫,否則獲取不到正確的值,如果不需要太多的欄位,自行刪減,
WechatOAuth.cs 核心類
using System.Collections.Generic;
namespace MrHuo.OAuth.Wechat
{
/// <summary>
/// Wechat OAuth 相關檔案參考:
/// <para>https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html</para>
/// </summary>
public class WechatOAuth : OAuthLoginBase<WechatAccessTokenModel, WechatUserInfoModel>
{
public WechatOAuth(OAuthConfig oauthConfig) : base(oauthConfig) { }
protected override string AuthorizeUrl => "https://open.weixin.qq.com/connect/oauth2/authorize";
protected override string AccessTokenUrl => "https://api.weixin.qq.com/sns/oauth2/access_token";
protected override string UserInfoUrl => "https://api.weixin.qq.com/sns/userinfo";
protected override Dictionary<string, string> BuildAuthorizeParams(string state)
{
return new Dictionary<string, string>()
{
["response_type"] = "code",
["appid"] = oauthConfig.AppId,
["redirect_uri"] = System.Web.HttpUtility.UrlEncode(oauthConfig.RedirectUri),
["scope"] = oauthConfig.Scope,
["state"] = state
};
}
public override string GetAuthorizeUrl(string state = "")
{
return $"{base.GetAuthorizeUrl(state)}#wechat_redirect";
}
protected override Dictionary<string, string> BuildGetAccessTokenParams(Dictionary<string, string> authorizeCallbackParams)
{
return new Dictionary<string, string>()
{
["grant_type"] = "authorization_code",
["appid"] = $"{oauthConfig.AppId}",
["secret"] = $"{oauthConfig.AppKey}",
["code"] = $"{authorizeCallbackParams["code"]}"
};
}
protected override Dictionary<string, string> BuildGetUserInfoParams(WechatAccessTokenModel accessTokenModel)
{
return new Dictionary<string, string>()
{
["access_token"] = accessTokenModel.AccessToken,
["openid"] = accessTokenModel.OpenId,
["lang"] = "zh_CN",
};
}
}
}
乍一看好多內容,懵了?先別懵,我一個一個來說一下:
protected override Dictionary<string, string> BuildAuthorizeParams(string state)
{
return new Dictionary<string, string>()
{
["response_type"] = "code",
["appid"] = oauthConfig.AppId,
["redirect_uri"] = System.Web.HttpUtility.UrlEncode(oauthConfig.RedirectUri),
["scope"] = oauthConfig.Scope,
["state"] = state
};
}
細心的讀者發現了,這一段就是為了構造 Authorize Url 時后邊的引數串列,回傳一個 Dictionary<string, string> 即可,以為微信公眾號把 client_id 欄位修改為 appid,所以這里需要處理一下,
public override string GetAuthorizeUrl(string state = "")
{
return $"{base.GetAuthorizeUrl(state)}#wechat_redirect";
}
這一段,在 Authorize Url 后邊綴了個 #wechat_redirect,雖然不知道微信在這個引數上做了什么文章(PS:知道的朋友,言傳一下~~),但是他檔案里寫就給他寫上吧,
protected override Dictionary<string, string> BuildGetAccessTokenParams(Dictionary<string, string> authorizeCallbackParams)
{
return new Dictionary<string, string>()
{
["grant_type"] = "authorization_code",
["appid"] = $"{oauthConfig.AppId}",
["secret"] = $"{oauthConfig.AppKey}",
["code"] = $"{authorizeCallbackParams["code"]}"
};
}
同理,這一段是為了構造 GetAccessToken 介面引數,
protected override Dictionary<string, string> BuildGetUserInfoParams(WechatAccessTokenModel accessTokenModel)
{
return new Dictionary<string, string>()
{
["access_token"] = accessTokenModel.AccessToken,
["openid"] = accessTokenModel.OpenId,
["lang"] = "zh_CN",
};
}
同理,這一段是為了構造 GetUserInfo 介面引數,
可以看到哈,這個框架本者自由、開放的原則,任何能自定義的地方,都可以自定義,還有我原本的出發點,并非只針對 OAuth 登錄這一個方向,我想把他平臺里面提供的 API 全部接入進來,因為擴展太容易了,但是吧,時間精力有限,再說人上了年紀,過了30歲,腦袋就不怎么靈光了,所以機會留給年輕人,
加入貢獻
我期待更多的朋友能加入到這個專案中,貢獻代碼也好,貢獻 appid 資源做測驗也好,提供意見建議也好,如果你也感興趣,請聯系我,
如果覺得有用幫到你了,貢獻幼兒園之星 ?,點個關注,fork 走一波~~(PS: 手動調皮)
相關檔案:
- OAuth2:https://oauth.net/2/
- Github: https://github.com/mrhuo/MrHuo.OAuth
- 官網:https://oauthlogin.net/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/248494.html
標籤:.NET技术
上一篇:WPF DataGrid與ListView性能對比與場景選擇
下一篇:開發者的代碼權限管理問題
