1. 程式人生 > 其它 >.NET 專案整合 OAuth2 登入最全面的、最方便的框架

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

MrHuo.OAuth 

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

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

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

已支援平臺

  • [x] 百度(可用)
  • [x] 微信公眾號(可用)
  • [x] Gitlab(可用)
  • [x] Gitee(可用)
  • [x] Github(可用)
  • [x] 華為(可用)
  • [x] Coding.net(可用)
  • [x] 新浪微博(可用)
  • [x] 支付寶(可用)
  • [x] OSChina(可用)
  • [x] 迅雷(可用)
  • [x] 釘釘內登入(可用)
  • [x] 釘釘掃碼登入(可用)
  • [x] QQ(可用)
  • [x] 微軟(可用)
  • [x] 小米(可用)
  • [x] StackOverflow(可用)
  • [x] Facebook(可用) by Donma Hsu
  • [x] Google(可用)
  • [x] LinkedIn(可用,待發布 nuget)
  • [x] 抖音(可用,待發布 nuget) by feng lui
  • [x] 快手(可用,待發布 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"  
    }  
  }  
}  
 

2、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);  
        }  
    }  
}  
 

3、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[6]

第一步:找平臺對應 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 做測試,有這方面資源的朋友聯絡我。提供測試的朋友,可以永久出現在專案首頁特別貢獻列表裡,可帶連結。郵件:[email protected] 備註:OAuth Appid

Contribution

1、歡迎參與開發,貢獻其他未完成平臺程式碼。

2、歡迎在 issue 裡提交需求平臺,帶上平臺連結地址,我們將加入到計劃之中。

3、歡迎提交各種建議,文明交流。

License

Apache-2.0 License

專案地址