.NET 專案整合 OAuth2 登入最全面、最方便的框架

.NET 專案整合 OAuth2 登入最全面、最方便的框架

MrHuo.OAuth 是 .NET 專案整合 OAuth2 登入最全面、最方便的框架

最後更新 2022/4/12 下午10:48
mrhuo
預計閱讀 8 分鐘
分類
.NET
專題
C#開源專案
標籤
.NET C# 開源 鑑權 開源C#

MrHuo.OAuth

是 .NET 專案整合 OAuth2 登入最全面、最方便的框架

Travis (.org) GitHub stars GitHub license

.NET Core 專案或 .NET Framework 4.6 專案均可使用

體驗網址:https://oauthlogin.net/


已支援平台

  • 百度(可用)
  • 微信公眾號(可用)
  • Gitlab(可用)
  • Gitee(可用)
  • GitHub(可用)
  • 華為(可用)
  • Coding.net(可用)
  • 新浪微博(可用)
  • 支付寶(可用)
  • OSChina(可用)
  • 迅雷(可用)
  • 釘釘內登入(可用)
  • 釘釘掃碼登入(可用)
  • QQ(可用)
  • 微軟(可用)
  • 小米(可用)
  • StackOverflow(可用)
  • Facebook(可用) by Donma Hsu
  • Google(可用)
  • LinkedIn(可用,待發行 nuget)
  • 抖音(可用,待發行 nuget) by feng lui
  • 快手(可用,待發行 nuget) by feng lui
  • 微信開放平台(待測試)
  • 美團(待測試)

計畫

  • 飛書
  • 淘寶
  • 西瓜
  • 今日頭條
  • 人人網
  • Teambition
  • Pinterest
  • Twitter
  • 企業微信二維碼登入
  • 企業微信網頁登入
  • 酷家樂
  • 餓了麼
  • 京東
  • 阿里雲
  • 喜馬拉雅...

使用方法

新建專案 web 專案,安裝 nuget 套件即可使用。

現可用的 nuget 套件列表如下:

https://www.nuget.org/packages?q=MrHuo.OAuth

Gitlab

Install-Package MrHuo.OAuth.Gitlab -Version 1.1.1

微信公眾號

Install-Package MrHuo.OAuth.Wechat -Version 1.1.1

oschina.net

Install-Package MrHuo.OAuth.OSChina -Version 1.1.1

coding.net

Install-Package MrHuo.OAuth.Coding -Version 1.1.1

github.com

Install-Package MrHuo.OAuth.GitHub -Version 1.1.1

alipay.com

Install-Package MrHuo.OAuth.Alipay -Version 1.1.1

baidu.com

Install-Package MrHuo.OAuth.Baidu -Version 1.1.1

huawei.com

Install-Package MrHuo.OAuth.Huawei -Version 1.1.1

gitee.com

Install-Package MrHuo.OAuth.Gitee -Version 1.1.1

weibo.com

Install-Package MrHuo.OAuth.SinaWeibo -Version 1.1.1

xunlei.com

Install-Package MrHuo.OAuth.XunLei -Version 1.1.1

qq.com

Install-Package MrHuo.OAuth.QQ -Version 1.1.1

microsoft.com

Install-Package MrHuo.OAuth.Microsoft -Version 1.1.1

mi.com

Install-Package MrHuo.OAuth.Mi -Version 1.1.1

stackoverflow.com

Install-Package MrHuo.OAuth.StackOverflow -Version 1.1.1

facebook.com

Install-Package MrHuo.OAuth.Facebook -Version 1.1.1

google.com

Install-Package MrHuo.OAuth.Google -Version 1.0.0
  1. Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    //將第三方登入元件注入進去
    services.AddSingleton(new Baidu.BaiduOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:baidu")));
    services.AddSingleton(new Wechat.WechatOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:wechat")));
    services.AddSingleton(new Gitlab.GitlabOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:gitlab")));
    services.AddSingleton(new Gitee.GiteeOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:gitee")));
    //... 其他登入方式
}

注意:如果用 appsettings.json 方式引入,提供了一個快捷方法從設定中載入。

OAuthConfig.LoadFrom(Configuration, "oauth:baidu")

"oauth:baidu" 這部分是設定前綴,設定格式如下:

{
  "oauth": {
    "qq": {
      "app_id": "qq_app_id",
      "app_key": "qq_app_key",
      "redirect_uri": "https://oauthlogin.net/oauth/qqcallback",
      "scope": "get_user_info"
    },
    "github": {
      "app_id": "github_app_id",
      "app_key": "github_app_key",
      "redirect_uri": "https://oauthlogin.net/oauth/githubcallback",
      "scope": "repo"
    },
    "wechat": {
      "app_id": "wechat_app_id",
      "app_key": "wechat_app_key",
      "redirect_uri": "https://oauthlogin.net/oauth/wechatcallback",
      "scope": "snsapi_userinfo"
    },
    "huawei": {
      "app_id": "huawei_app_id",
      "app_key": "huawei_app_key",
      "redirect_uri": "https://oauthlogin.net/oauth/huaweicallback",
      "scope": "https://www.huawei.com/auth/account"
    },
    "gitee": {
      "app_id": "gitee_app_id",
      "app_key": "gitee_app_key",
      "redirect_uri": "http://oauthlogin.net/oauth/giteecallback",
      "scope": "user_info"
    },
    "baidu": {
      "app_id": "baidu_app_id",
      "app_key": "baidu_app_key",
      "redirect_uri": "http://oauthlogin.net/oauth/baiducallback",
      "scope": "basic"
    },
    "alipay": {
      "app_id": "alipay_app_id",
      "app_key": "alipay_app_key",
      "redirect_uri": "https://oauthlogin.net/oauth/alipaycallback",
      "scope": "auth_user",
      "private_key": "private_key",
      "public_key": "public_key"
    },
    "gitlab": {
      "app_id": "gitlab_app_id",
      "app_key": "gitlab_app_key",
      "redirect_uri": "http://oauthlogin.net/oauth/gitlabcallback",
      "scope": "read_user"
    }
  }
}
  1. OAuthController.cs 根據實際需要自行命名
public class OAuthController : Controller
{
    [HttpGet("oauth/{type}")]
    public IActionResult Index(
        string type,
        [FromServices] BaiduOAuth baiduOAuth,
        [FromServices] WechatOAuth wechatOAuth
    )
    {
        var redirectUrl = "";
        switch (type.ToLower())
        {
            case "baidu":
                {
                    redirectUrl = baiduOAuth.GetAuthorizeUrl();
                    break;
                }
            case "wechat":
                {
                    redirectUrl = wechatOAuth.GetAuthorizeUrl();
                    break;
                }
            default:
                return ReturnToError($"沒有實作【{type}】登入方式!");
        }
        return Redirect(redirectUrl);
    }

    [HttpGet("oauth/{type}callback")]
    public async Task<IActionResult> LoginCallback(
        string type,
        [FromServices] BaiduOAuth baiduOAuth,
        [FromServices] WechatOAuth wechatOAuth,
        [FromQuery] string code,
        [FromQuery] string state)
    {
        try
        {
            switch (type.ToLower())
            {
                case "baidu":
                    {
                        var authorizeResult = await baiduOAuth.AuthorizeCallback(code, state);
                        if (!authorizeResult.IsSccess)
                        {
                            throw new Exception(authorizeResult.ErrorMessage);
                        }
                        return Json(authorizeResult);
                    }
                case "wechat":
                    {
                        var authorizeResult = await wechatOAuth.AuthorizeCallback(code, state);
                        if (!authorizeResult.IsSccess)
                        {
                            throw new Exception(authorizeResult.ErrorMessage);
                        }
                        return Json(authorizeResult);
                    }
                default:
                    throw new Exception($"沒有實作【{type}】登入回呼!");
            }
        }
        catch (Exception ex)
        {
            return Content(ex.Message);
        }
    }
}
  1. Views
<!--在程式碼中放置授權按鈕-->
<a href="/oauth/baidu">Baidu 登入</a>
<a href="/oauth/wechat">Wechat 掃碼登入</a>
<!-- //其他登入方式照樣往下寫 -->

擴充

擴充其他平台非常容易,拿 Gitee 平台的程式碼來說:https://github.com/mrhuo/MrHuo.OAuth/tree/main/MrHuo.OAuth.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; }

    //...其他屬性類似如上
}
第二步:寫對應平台的授權介面
/// <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 標準開發,那麼就這麼幾行就好了。

就連修改欄位的微信登入實作,也不過複雜,只需要定義基本參數就 OK。程式碼如下:

/// <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",
        };
    }
}

特別貢獻

  1. Carl
  2. Donma Hsu
  3. feng lui

為了能讓各位朋友能順利的使用各種平台登入元件,先急求各種平台的 APPID 做測試,有這方面資源的朋友聯絡我。 提供測試的朋友,可以永久出現在專案首頁特別貢獻列表裡,可帶連結。

郵件:admin@mrhuo.com 備註:OAuth Appid

Contribution

1.歡迎參與開發,貢獻其他未完成平台程式碼。 2.歡迎在 issue 裡提交需求平台,帶上平台連結位址,我們將加入到計畫之中。 3.歡迎提交各種建議,文明交流。

License

Apache-2.0 License

專案位址

MrHuo.OAuth

繼續探索

延伸閱讀

更多文章
同分類 / 同標籤 2026/2/7

AOT使用經驗總結

從專案建立伊始,就應養成良好的習慣,即只要添加了新功能或使用了較新的語法,就及時進行 AOT 發布測試。

繼續閱讀