不少對外應用的開發都考慮接入第三方登陸來提升用戶的體驗感,避免用戶進行繁瑣的註冊登陸(登陸後的完善資料必不可免)。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 創做不易,任何人或團體、機構所有轉載或者部分轉載、摘錄,請在文章明顯位置註明做者和原文連接。
|