不少对外应用的开发都考虑接入第三方登陆来提升用户的体验感,避免用户进行繁琐的注册登陆(登陆后的完善资料必不可免)。html
而QQ、微信、支付宝、淘宝、微博等应用就是首选目标(无他,用户群体大,支持发开发者受权应用)。git
能够点击下面的地址体验一下。github
下面介绍基于OAuth2 的登陆组件 微信
这里使用 GitHub 登陆作演示,由于GitHub的 开发者应用程序 的建立支持localhost的方式访问,能够本地开发直接调用。app
新建一个 Asp.Net Core Web 应用(模型-视图-控制器) 项目,项目名 GithubLogin (你也能够起一个其余的名称),选择 .Net Core 3.1 (长期支持) 后建立项目。
async
MrHuo.OAuth.Github 学习
选择1.0.0进行安装网站
访问 https://github.com/settings/applications/new 网站
this
注意:GitHub网站速度较慢,若是显示 没法访问此网站 刷新一下多执行几回,或者使用第二种入口注册。
访问 https://github.com/ 进行登陆,在右上角的头像图标旁边下拉点击设置 Settings,
在出来的页面点击开发者设置 Developer settings ,
选择 OAuth App 应用程序,点击 New OAuth App 建立OAuth应用程序
把界面里的 Client ID
,Client secret
,连同上一个界面里填写的 Authorization callback URL
所有填写到配置文件对应位置。如今配置文件 appsettings.json
是这样的:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*", "oauth": { "github": { "app_id": "c147cxxxxxxxxxxxxxxxxxxe6ea2", //OAuth App建立的Client ID "app_key": "03ef6xxxxxxxxxbe6f4f0febef5", //OAuth App建立的Client secrets "redirect_uri": "http://localhost:33180/oauth/githubcallback", //回调地址(这个地址是你本身写的,后面受权成功后作本身须要的功能) "scope": "repo" } } }
在 Startup.cs
文件的ConfigureServices方法中注入组件:
services.AddSingleton(new GithubOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:github")));
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); //注入GitHub受权组件 services.AddSingleton(new GithubOAuth(OAuthConfig.LoadFrom(Configuration, "oauth:github"))); }
在Controllers新建OAuthController.cs类,里面的代码以下:
using Microsoft.AspNetCore.Mvc; using MrHuo.OAuth.Github; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ThirdPartyLogin.Controllers { public class OAuthController : Controller { #region GitHub受权+回调 //发起第三方受权申请 [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)); } #endregion } }
而后运行程序,在地址栏手动输入访问 发起第三方受权申请 的方法:http://localhost:33180/oauth/github 跳转到受权页面,
以下,点击绿色的按钮赞成,而后受权成功,
成功后调用咱们以前配置的回调方法,在这里咱们就能够自定义操做了,入库或者其余。
受权成功返回的内容以下:
通过指定处理后,可视化显示为:
到这里一个简单的第三方GitHub受权指定网站登陆就完成了,其余的受权都是大同小异,须要注意的是咱们用到的组件须要去找一下,而后去各个平台申请一个key。
固然,我这里是白嫖的 开发者精选资讯 大佬的,更多用法能够直接去下载demo下来看,最后附上连接,你们能够去看看
欢迎关注订阅微信公众号【熊泽有话说】,更多好玩易学知识等你来取
做者:熊泽-学习中的苦与乐 公众号:熊泽有话说 出处:https://www.cnblogs.com/xiongze520/p/15039407.html 创做不易,任何人或团体、机构所有转载或者部分转载、摘录,请在文章明显位置注明做者和原文连接。
|