- A+
所属分类:.NetCore
第三方登录的原理
所谓第三方登录,实质就是 OAuth 授权。用户想要登录 A 网站,A 网站让用户提供第三方网站的数据,证明自己的身份。获取第三方网站的身份数据,就需要 OAuth 授权。
举例来说,A 网站允许 GitHub 登录,背后就是下面的流程。
- A 网站让用户跳转到 GitHub。
- GitHub 要求用户登录,然后询问"A 网站要求获得 xx 权限,你是否同意?"
- 用户同意,GitHub 就会重定向回 A 网站,同时发回一个授权码。
- A 网站使用授权码,向 GitHub 请求令牌。
- GitHub 返回令牌.
- A 网站使用令牌,向 GitHub 请求用户数据。
应用登记
一个应用要求 OAuth 授权,必须先到对方网站登记,让对方知道是谁在请求。
所以,你要先去 GitHub 登记一下。当然,我已经登记过了,你使用我的登记信息也可以,但为了完整走一遍流程,还是建议大家自己登记。这是免费的。
访问https://github.com/settings/applications/new,填写登记表。
提交表单以后,GitHub 应该会返回客户端 ID(client ID)和客户端密钥(client secret),这就是应用的身份识别码。
代码示例
用到的接口
- 获取code [get]
- https://github.com/login/oauth/authorize?client_id=eb36d61e44aa9a553cc8&redirect_uri=https://localhost:44341/Demo/Test.html
- 获取Token [post]
- https://github.com/login/oauth/access_token?client_id=eb36d61e44aa9a553cc8&client_secret=ecbd5ce648f14f1ef3c8564d325ab3f13dc5bd7d&code=07537a84d12bbae08361
- 获取授权信息 [get]
- https://api.github.com/user?access_token=803c8af0237b8d2ba487250c7f808cbb378fbd0f
Html代码
- <button data-method="GitHubOAuth" class="layui-btn">GitHubOAuth</button>
- GitHubOAuth: function () {
- window.location.href = "https://localhost:44341/GitHubOAuth/Index";
- }
dotNet代码
- public readonly string client_id = "eb36d61e44aa9a553cc8";
- private readonly string client_secret = "ecbd5ce648f14f1ef3c8564d325ab3f13dc5bd7d";
- /// <summary>
- /// 重定向用户请求GitHub身份
- /// </summary>
- /// <returns></returns>
- public IActionResult Index()
- {
- return Redirect($"https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri=https://localhost:44341/GitHubOAuth/OAuth");
- }
- /// <summary>
- /// OAuth授权信息
- /// </summary>
- /// <param name="code"></param>
- /// <returns></returns>
- public IActionResult OAuth(string code)
- {
- HttpResult AccessToken = GetAccessToken(code);
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem()
- {
- URL = $"https://api.github.com/user?{AccessToken.Html.Trim()}",
- Method = "get"
- };
- HttpResult result = http.GetHtml(item);
- return Content(result.Html);
- }
- /// <summary>
- /// 获取AccessToken
- /// </summary>
- /// <param name="code"></param>
- /// <returns></returns>
- public HttpResult GetAccessToken(string code) {
- HttpHelper http = new HttpHelper();
- HttpItem item = new HttpItem() {
- URL= $"https://github.com/login/oauth/access_token?client_id={client_id}&client_secret={client_secret}&code={code}",
- Method="post"
- };
- HttpResult result = http.GetHtml(item);
- return result;
- }
效果预览
现在我们就拿到了用户信息 可以自己进行扩展应用了