1. 程式人生 > >.netcore 急速接入第三方登入,不看後悔

.netcore 急速接入第三方登入,不看後悔

![](https://static01.imgkr.com/temp/84b5772d13134dd09019c35da3765f2b.png) 新年新氣象,趁著新年的喜慶,肝了十來天,終於發了第一版,希望大家喜歡。 > 如果有不喜歡看文字的童鞋,可以直接看下面的地址體驗一下:
`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` 登入做演示的原因。 ![](https://imgkr2.cn-bj.ufileos.com/d7665d12-547e-422e-9fed-fa5ca463867c.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=2q%252Bo8vy5oy%252Foqne5OWIbxpuNH9E%253D&Expires=1610653563) 建立完成後,在這個介面裡生成 `client secret`: ![](https://static01.imgkr.com/temp/db287e3a14684ff2ba33293ed9104707.png) 輸入密碼,生成成功後是這樣的: ![](https://imgkr2.cn-bj.ufileos.com/2af60b6d-efc8-410b-a688-6cf125208d75.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=NsSqfI6jmhWTej0AjQg7q%252FXJ7h8%253D&Expires=1610653750) 把介面裡的 `Client ID`,`Client secret`,連同上一個介面裡填寫的 `Authorization callback URL` 全部填寫到配置檔案對應位置。現在配置檔案 `appsettings.json` 是這樣的: ```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` 檔案中注入元件: ```csharp // 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` 類,程式碼如下: ```csharp 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 GithubCallback( [FromServices] GithubOAuth githubOAuth, [FromQuery] string code) { return Json(await githubOAuth.AuthorizeCallback(code)); } } } ``` 你沒看錯,就這點程式碼就好了。我們來執行一下試試: ![](https://static01.imgkr.com/temp/45685018a07245c8a7f7896e35a30c12.png) 專案執行之後,在位址列裡輸入下面這個地址:`http://localhost:5000/oauth/github`,因為我們沒有修改任何程式碼,沒有在檢視上做任何連結,所以就勞煩手動啦~~ 回車之後,順利跳轉到 `github` 授權: ![](https://static01.imgkr.com/temp/0076b15cc30744b1b9ebf173fb981983.png) 點選綠色的 `Authorize` 按鈕之後稍等片刻,你會看到下面這個結果: ![](https://static01.imgkr.com/temp/8b51c0cffba548daaa973ac7ab5f2a6f.png) 順利拿到了使用者資訊(PS:請忽略我少的可憐的粉絲,曾經我不強求 --ToT) ![](https://imgkr2.cn-bj.ufileos.com/0c7d8ecd-1633-48a1-8b38-284345a8c7b0.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=gwfLQKYQqmoSnmX%252BKTZlDl3U%252FwU%253D&Expires=1610655014) 好了,到這裡我的表演結束了,可以看到接入流程非常流程,卡人主要是在申請這些步驟。下面講講原理之類的,隨便說一些...如果覺得我囉嗦,那麼就不用往下看了,因為下面我會更囉嗦。 當然,除了 `github` 現在已經接入了12個平臺,其中 `QQ` 和抖音我沒有註冊到應用,無法測試,所以暫時沒有 `nuget` 包,一個人的力量總是有限的,在這裡我請求各位有閒時間或者有 `appid` 資源的大佬,為這個小專案做一些貢獻,是她走的遠一些。 ![](https://static01.imgkr.com/temp/71e4771961ed42828f0f21ecb46cfb46.png) 更多的 `nuget` 包,進這裡 `https://www.nuget.org/profiles/mrhuo` 或者在 VS nuget 包管理器裡搜尋 `MrHuo.OAuth`,就可以了。 > 請忽略 `nuget` 上其他幾個 `垃圾` 包,那是很多年很多年以前寫的,捨不得刪。 ## 開發背景 第三方平臺登入說白了就是實現 `OAuth2` 協議,很多平臺比如支付寶、百度、github、微軟,甚至是抖音、快手很多平臺都提供了開放介面。但是,很多平臺會在這個標準協議的基礎上增加、修改一些東西,比如:標準協議裡,獲取 `authorize code` 時應提供 `client_id`,微信公眾平臺非要把它改成 `appid`。再比如:獲取使用者資訊時,只需要 `access_token` 引數,微信公眾平臺這邊非要提供一個 `openid`,當然這是在所難免的,因為各個平臺實際業務還是千差萬別,無法做到完全的統一,那這就給我們開發者帶來一個困擾,開發第三方登入時很困難,當然,開發一兩個也無所謂,要是多了呢? 假如有這麼一個產品經理,他想接入很多的登入方式,讓使用者無論使用哪種平臺,都能在這裡順利登入,找到回家的路呢(PS:產品經理你別跑,看我40米的大刀)。 ![](https://imgkr2.cn-bj.ufileos.com/42deba00-15b6-49d2-afb6-7dcd1fd2c10d.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=O39mc6vUsoIhHI6VYb6F1GP8hL4%253D&Expires=1610651734) 無疑,給我們一個考驗,如何做到一個標準化,可配置,可擴充套件呢?這就是一個需要深究的問題。下面我就說說我肝這個專案的一些想法,說的不好別噴我,我還年輕(PS:三十多歲老大叔別裝嫩),還要臉...... ![](https://static01.imgkr.com/temp/e3e1d08ef5234246806c3b01cb568297.png) ## 制定標準 看了很多文件之後,我們會發現,萬變不離其宗,總有規律可循,總的來說,有下面3個步驟: 1. `GetAuthorizeUrl` 這一步通過 `client_id`,`redirect_uri` 等幾個引數來獲取授權 `url`,跳轉到這個 `url` 之後將在第三方平臺上完成登入,完成登入之後會跳轉到上面提供的 `redirect_uri` 這個地址,並且帶上一個 `code` 引數。 2. `GetAccessToken` 這一步裡,拿到上面的 `code` 之後去第三方平臺換 `access_token`。 3. `GetUserInfo` 這一步並非必須,但是我們既然是做第三方登入,登入之後還是需要和自己平臺的一些業務繫結使用者賬號,或者使用現有資訊註冊一個使用者,這個方法就顯得尤為重要了。 到此,就這3個步驟,我覺得時需要制定在標準裡面的,所以我就寫了下面這個介面來規範它: ```csharp /// /// OAuth 登入 API 介面規範 ///
public interface IOAuthLoginApi where TAccessTokenModel : IAccessTokenModel where TUserInfoModel : IUserInfoModel { /// /// 獲取跳轉授權的 URL /// /// /// string GetAuthorizeUrl(string state = ""); /// /// 非同步獲取 AccessToken /// /// /// /// Task GetAccessTokenAsync(string code, string state = ""); /// /// 非同步獲取使用者詳細資訊 /// /// /// Task GetUserInfoAsync(TAccessTokenModel accessTokenModel); } ``` 可以看到我將 `AccessToken` 和 `UserInfo` 做成了泛型引數,因為他們是這個規範裡的可變部分。程式碼中 `state` 引數的作用呢就是為了防止 `CORS` 攻擊做的防偽驗證,這裡暫不做解釋,其他文件裡都有這個引數的解釋。 ![](https://imgkr2.cn-bj.ufileos.com/80587ef8-5717-4cc7-929f-490eb888523b.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=SncgXmscoh%252FwLalYAglqIDkfprI%253D&Expires=1610658050) ## 如何擴充套件新的平臺 這裡拿 `Gitee` 來做演示: #### 第一步:找平臺對應 OAuth 文件,找到獲取使用者資訊介面返回JSON,轉換為 C# 實體類。如下: > 根據自己需要和介面標準,擴充套件使用者屬性 ```csharp 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` 序列化庫,據說效能提高了不少! #### 第二步:寫對應平臺的授權介面 ```csharp /// /// https://gitee.com/api/v5/oauth_doc#/ /// public class GiteeOAuth : OAuthLoginBase { 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 類擴充套件 ```csharp namespace MrHuo.OAuth.Wechat { public class WechatAccessTokenModel : DefaultAccessTokenModel { [JsonPropertyName("openid")] public string OpenId { get; set; } } } ``` > 繼承自 `DefaultAccessTokenModel`,新增欄位 `OpenId`,因為獲取使用者資訊需要獲取 `OpenId`,所以這裡需要它。 `WechatUserInfoModel.cs` 使用者資訊類 ```csharp 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; } /// /// 使用者特權資訊,json 陣列,如微信沃卡使用者為(chinaunicom) /// [JsonPropertyName("privilege")] public List Privilege { get; set; } [JsonPropertyName("unionid")] public string UnionId { get; set; } [JsonPropertyName("errmsg")] public string ErrorMessage { get; set; } } } ``` > 這裡使用者資訊欄位上邊的 `[JsonPropertyName("xxxx")]` 完全按照文件裡的欄位寫,否則獲取不到正確的值。如果不需要太多的欄位,自行刪減。 `WechatOAuth.cs` 核心類 ```csharp using System.Collections.Generic; namespace MrHuo.OAuth.Wechat { /// /// Wechat OAuth 相關文件參考: /// https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html /// public class WechatOAuth : OAuthLoginBase { 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 BuildAuthorizeParams(string state) { return new Dictionary() { ["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 BuildGetAccessTokenParams(Dictionary authorizeCallbackParams) { return new Dictionary() { ["grant_type"] = "authorization_code", ["appid"] = $"{oauthConfig.AppId}", ["secret"] = $"{oauthConfig.AppKey}", ["code"] = $"{authorizeCallbackParams["code"]}" }; } protected override Dictionary BuildGetUserInfoParams(WechatAccessTokenModel accessTokenModel) { return new Dictionary() { ["access_token"] = accessTokenModel.AccessToken, ["openid"] = accessTokenModel.OpenId, ["lang"] = "zh_CN", }; } } } ``` 乍一看好多內容,懵了?先別懵,我一個一個來說一下: ```csharp protected override Dictionary BuildAuthorizeParams(string state) { return new Dictionary() { ["response_type"] = "code", ["appid"] = oauthConfig.AppId, ["redirect_uri"] = System.Web.HttpUtility.UrlEncode(oauthConfig.RedirectUri), ["scope"] = oauthConfig.Scope, ["state"] = state }; } ``` 細心的讀者發現了,這一段就是為了構造 `Authorize Url` 時後邊的引數列表,返回一個 `Dictionary` 即可,以為微信公眾號把 `client_id` 欄位修改為 `appid`,所以這裡需要處理一下。 ```csharp public override string GetAuthorizeUrl(string state = "") { return $"{base.GetAuthorizeUrl(state)}#wechat_redirect"; } ``` 這一段,在 `Authorize Url` 後邊綴了個 `#wechat_redirect`,雖然不知道微信在這個引數上做了什麼文章(PS:知道的朋友,言傳一下~~),但是他文件裡寫就給他寫上吧。 ```csharp protected override Dictionary BuildGetAccessTokenParams(Dictionary authorizeCallbackParams) { return new Dictionary() { ["grant_type"] = "authorization_code", ["appid"] = $"{oauthConfig.AppId}", ["secret"] = $"{oauthConfig.AppKey}", ["code"] = $"{authorizeCallbackParams["code"]}" }; } ``` 同理,這一段是為了構造 `GetAccessToken` 介面引數。 ```csharp protected override Dictionary BuildGetUserInfoParams(WechatAccessTokenModel accessTokenModel) { return new Dictionary() { ["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://oauthlo