日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

aspnet登录界面代码_SPA+.NET Core3.1 GitHub第三方授权登录

發布時間:2025/3/12 asp.net 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 aspnet登录界面代码_SPA+.NET Core3.1 GitHub第三方授权登录 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

GitHub第三方授權登錄

有許多文章都講過GitHub第三方授權登錄,但就是沒有.NET?Core配合前后端分離的項目(Vue,React)的實踐。所以本文以前后端分離項目中如何在授權登錄后,生成Token的過程。

后端 .NET Core,使用類庫AspNet.Security.OAuth.GitHub

前端技術棧如下:VUE+Vue-Router+axios

AspNet.Security.OAuth.GitHub

  • GitHub?https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers

GitHub授權登錄

什么配置的過程不說了,有許多文章都講過,這里不詳細展開。直接看配置的內容。

可參考如下網站

  • GitHub 第三方登錄 https://www.jianshu.com/p/78d186aeb526

  • 給你的網站添加第三方登錄以及短信驗證功能 https://juejin.im/post/5dfb04cee51d45583a66c2f3

配置后,我們能得到一個client_id,client_secret,這里是我創建的一個應用test。配置如下。

得到的client_id,client_secret在下面會用到。

client_id:0be6b05fc717bfc4fb67
client_secret:dcaced9f176afba64e89d88b9b06ffc4a887a609

瀏覽器打開下面地址,Get請求,替換自己的client_id

https://github.com/login/oauth/authorize?client_id=0be6b05fc717bfc4fb67&redirect_uri=https://localhost:5001/signin-github

會重定向到

https://localhost:5001/signin-github?code=07537a84d12bbae08361

這個code放到下面的請求中,會得到一個獲取access_token

以POST方式(PostMan去請求)

https://localhost:5001/signin-github?code=07537a84d12bbae08361

這個code放到下面的請求中,獲取access_token POST方式(PostMan去請求)

https://github.com/login/oauth/access_token?client_id=0be6b05fc717bfc4fb67&client_secret=dcaced9f176afba64e89d88b9b06ffc4a887a609&code=07537a84d12bbae08361

Get方式請求如下地址,攜帶上一個POST的access_token值。

https://api.github.com/user?access_token=787506afa3271d077b98f18af56d7cfdc8db43b4

然后就能獲取用戶信息

{
"login": "luoyunchong",
"id": 18613266,
"node_id": "MDQ6VXNlcjE4NjEzMjY2",
"avatar_url": "https://avatars1.githubusercontent.com/u/18613266?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/luoyunchong",
"html_url": "https://github.com/luoyunchong",
"followers_url": "https://api.github.com/users/luoyunchong/followers",
"following_url": "https://api.github.com/users/luoyunchong/following{/other_user}",
"gists_url": "https://api.github.com/users/luoyunchong/gists{/gist_id}",
"starred_url": "https://api.github.com/users/luoyunchong/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/luoyunchong/subscriptions",
"organizations_url": "https://api.github.com/users/luoyunchong/orgs",
"repos_url": "https://api.github.com/users/luoyunchong/repos",
"events_url": "https://api.github.com/users/luoyunchong/events{/privacy}",
"received_events_url": "https://api.github.com/users/luoyunchong/received_events",
"type": "User",
"site_admin": false,
"name": "IGeekFan",
"company": null,
"blog": "https://blog.igeekfan.cn",
"location": null,
"email": "luoyunchong@foxmail.com",
"hireable": null,
"bio": "學習之路漫漫無期。",
"public_repos": 14,
"public_gists": 0,
"followers": 16,
"following": 11,
"created_at": "2016-04-22T10:33:44Z",
"updated_at": "2019-12-21T14:49:33Z"
}

.NET Core3.1

講完了GitHub授權登錄的過程,我們來說一個在.NET?Core下的實踐。以下代碼為主要代碼,完整代碼請看查看最下面的鏈接。

  • 前端運行在:http://localhost:8081

  • 后端運行在:https://localhost:5001

  • 本地測試時GitHub回調地址設置:?https://localhost:5001/signin-github。

GitHub回調地址設置 http(s)://ip:端口/signin-github

1. Github授權登錄回調地址明明填寫的是后端的地址,那后端怎么把結果通知前端呢?

我們先來了解一些登錄的流程。

GitHub登錄流程:前端放一個GitHub登錄的按鈕,點擊后,調用signin方法,然后調用后臺接口signin方法。

  • 提供參數provider為GitHub,

  • redirectUrl為GitHub授權登錄后,回調signin-github后,后端要重定向的地址,這里填前端的一個路由。

type="primary" @click="signin">GitHub登錄
<script>export default {name: "app",components: {},methods: {
signin() {window.open("https://localhost:5001/signin?provider=GitHub&redirectUrl=http://localhost:8080/login-result"
);
}
}
};script>

2. 后端只提供了signin,signin-callback路由,沒有signin-github,那github上配置的路由是怎么回調回來呢?

google-登錄,微軟文檔,在這個文檔中有詳細的關于外部登錄設置,其中有一個更改默認回調 URI,通過 AddGitHub中的CallbackPath屬性配置。

介紹了回調地址應配置signin-google,所以這里應該是signin-github,他是可以配置的,不需要自己寫程序處理signin-google這個路由,內部有中間件已經處理了。

3. 回調到signin-github后,后端怎么處理,才能讓前端刷新。獲取登錄后的信息呢。

具體上面的根據code獲取access_token,根據access_token獲取用戶的信息的過程,這些處理的過程,都不需要我們自己處理。我們可以用直接獲取用戶信息。

一個方法SignIn,只要return Challenge(properties, provider);,

  • provider 為 GitHub,

  • properties 是對象 var properties = new AuthenticationProperties { RedirectUri = url };

  • url:https://localhost:5001/signin-callback?provider=GitHub&redirectUrl=http://localhost:8080/login-result

前臺傳的參數為GitHub和redirectUrl.這個url是回調sigin-github后,這個類庫幫我們重定向的地址。我們只要拼接好地址,讓他回調到signin-callback方法即可。

var request = _contextAccessor.HttpContext.Request;
var url = $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}-callback?provider={provider}&redirectUrl={redirectUrl}";

需要注入

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
}private readonly IHttpContextAccessor _contextAccessor;
public AuthenticationController( IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}

signin-callback方法,我們可通過如下方法獲取到授權登錄的email值,name值。

var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;
string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;

代碼實現

打開NuGet包管理,安裝包

Install-Package AspNet.Security.OAuth.GitHub

appSettings.json

"Authentication": {
"GitHub": {
"ClientId": "0be6b05fc717bfc4fb67",
"ClientSecret": "dcaced9f176afba64e89d88b9b06ffc4a887a609"
}
}

add擴展方法 因為我們要生成一個Token值,所以我們需要配置Jwt, 這里增加一個擴展方法。

public static class JwtConfiguration
{
public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration)
{

services.AddAuthentication(opts =>
{
opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddCookie().AddGitHub(options =>
{
options.ClientId = configuration["Authentication:GitHub:ClientId"];
options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
});
}
}

默認情況下,如頭像,email,是沒有獲取的。

.AddGitHub(options =>
{
options.ClientId = configuration["Authentication:GitHub:ClientId"];
options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
//options.CallbackPath = new PathString("~/signin-github");//與GitHub上的回調地址相同,默認即是/signin-github
options.Scope.Add("user:email");
//authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value; 得到GitHub頭像
options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
options.ClaimActions.MapJsonKey(LinConsts.Claims.BIO, "bio");
options.ClaimActions.MapJsonKey(LinConsts.Claims.BlogAddress, "blog");
});

#其中LinConsts類為靜態常量
public static class LinConsts
{
public static class Claims
{
public const string BIO = "urn:github:bio";
public const string AvatarUrl = "urn:github:avatar_url";
public const string BlogAddress = "urn:github:blog";
}
}

startup.cs

ConfigureServices中配置此服務

services.AddSingletonHttpContextAccessor>();
services.AddJwtConfiguration(Configuration);

創建AuthenticationController.cs 增加SignIn,用于處理用戶授權成功后,重定回signin-callback,并將參數帶回。

private readonly IHttpContextAccessor _contextAccessor;
private readonly IConfiguration _configuration;

public AuthenticationController(IHttpContextAccessor contextAccessor, IConfiguration configuration)
{
_contextAccessor = contextAccessor;
_configuration = configuration;
}

[HttpGet("~/signin")]
public async TaskSignIn(string provider, string redirectUrl)
{
var request = _contextAccessor.HttpContext.Request;
var url =
$"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}-callback?provider={provider}&redirectUrl={redirectUrl}";
var properties = new AuthenticationProperties { RedirectUri = url };
properties.Items["LoginProviderKey"] = provider;
return Challenge(properties, provider);

}

在signin方法中,用戶點擊授權后(第一次),會根據其傳遞的URL,重定向到這個地址,signin-callback,參數也會一同攜帶。provider為GitHub,redirectUrl為:http://localhost:8081/login-result.

[HttpGet("~/signin-callback")]
public async TaskHome(string provider = null, string redirectUrl = "")
{
var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);if (!authenticateResult.Succeeded) return Redirect(redirectUrl);
var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier);if (openIdClaim == null || string.IsNullOrWhiteSpace(openIdClaim.Value))
return Redirect(redirectUrl);//TODO 記錄授權成功后的信息 string email = authenticateResult.Principal.FindFirst(ClaimTypes.Email)?.Value;string name = authenticateResult.Principal.FindFirst(ClaimTypes.Name)?.Value;string gitHubName = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Name)?.Value;string gitHubUrl = authenticateResult.Principal.FindFirst(GitHubAuthenticationConstants.Claims.Url)?.Value;//startup 中 AddGitHub配置項 options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");string avatarUrl = authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value;
return Redirect($"{redirectUrl}?openId={openIdClaim.Value}");
}

這時候我們能獲取用戶信息了。那么前端怎么辦呢。我們寫個方法,獲取用戶信息,看看效果。

  • 瀏覽器直接打開能得到github的id。

  • axios GET請求?https://localhost:5001/OpenId?得到null

[HttpGet("~/OpenId")]
public async Task<string> OpenId(string provider = null)
{
var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
if (!authenticateResult.Succeeded) return null;
var openIdClaim = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier);
return openIdClaim?.Value;
}

我記得之前傳Token時,后臺是可以這樣獲取的。

[HttpGet("~/GetOpenIdByToken")]
public string GetOpenIdByToken()
{
return User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}

LoginResult.vue在created生命周期中。都是得到null

axios({
methods: "get",
url: "https://localhost:5001/OpenId?provider=GitHub"
})
.then(function(response) {
// handle success
console.log(response);
})

axios({
methods: "get",
url: "https://localhost:5001/GetOpenIdByToken"
})
.then(function(response) {
// handle success
console.log(response);
})

為什么呢???

因為前后端分離,不是基于Cookies的。http是無狀態的。每次請求無法區分用戶的。我們可以根據當前的ClaimsPrincipal,根據JWT生成相應的Token,axios請求時,放到headers中。

安裝包

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

AppSettings.json配置改成

"Authentication": {
"JwtBearer": {
"SecurityKey": "JWTStudyWebsite_DI20DXU3",
"Issuer": "JWTStudy",
"Audience": "JWTStudyWebsite"
},
"GitHub": {
"ClientId": "0be6b05fc717bfc4fb67",
"ClientSecret": "dcaced9f176afba64e89d88b9b06ffc4a887a609"
}
}

在signin-callback路由中,得到authenticateResult.Principal,其中默認包含了(id,login,name,url),授權得到eamil,另外MapJsonKey擴展了以下字段(avatar_url、bio、blog)

var authenticateResult = await _contextAccessor.HttpContext.AuthenticateAsync(provider);
string token = this.CreateToken(authenticateResult.Principal);

根據ClaimsPrincipal值生成token值。

private string CreateToken(ClaimsPrincipal claimsPrincipal)
{

var handler = new JwtSecurityTokenHandler();
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration["Authentication:JwtBearer:SecurityKey"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_configuration["Authentication:JwtBearer:Issuer"],
_configuration["Authentication:JwtBearer:Audience"],
claimsPrincipal.Claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: credentials
);

return handler.WriteToken(token);
}

這里的claimsPrincipal是什么呢。簡單的說就是一個存有github授權信息的對象,可以解析出對應的Clamis,這里其實就是用了Clamis的屬性值。

ClaimClaimsIdentityClaimsPrincipal
id、name,url,email,avatar_url等由多組Claim組成,這里可指GitHub授權登錄后得到的那個對象。ClaimsIdentity的持有者

具體Jwt的生成與配置項。這里不詳細說明。可以看這個示例(.NET Core2.2)https://github.com/luoyunchong/BasicTemplate

AddJwtConfiguration改成如下內容

public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration)
{

services.AddAuthentication(opts =>
{
opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/signin";
options.LogoutPath = "/signout";
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.Audience = configuration["Authentication:JwtBearer:Audience"];

options.TokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),

// Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],

// Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = configuration["Authentication:JwtBearer:Audience"],

// Validate the token expiry
ValidateLifetime = true,

// If you want to allow a certain amount of clock drift, set that here
//ClockSkew = TimeSpan.Zero
};
}).AddGitHub(options =>
{
options.ClientId = configuration["Authentication:GitHub:ClientId"];
options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
//options.CallbackPath = new PathString("~/signin-github");//與GitHub上的回調地址相同,默認即是/signin-github
options.Scope.Add("user:email");
//authenticateResult.Principal.FindFirst(LinConsts.Claims.AvatarUrl)?.Value; 得到GitHub頭像
options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
options.ClaimActions.MapJsonKey(LinConsts.Claims.BIO, "bio");
options.ClaimActions.MapJsonKey(LinConsts.Claims.BlogAddress, "blog");
});
}

前端完整的LoginResult.vue代碼

即 localhost:8080/login-result

<template><div class="main"><h2>Login-Resulth2><p>OpenId:{{OpenId1}}p><p>GetOpenIdByToken{{OpenId2}}p>div>template><script>const axios = require("axios");function parseUrlParams() {if (window.location.search.length <= 0) return false;var info = window.location.search.slice(1);var result = {};
info.split("&").forEach(item => {
result[decodeURIComponent(item.split("=")[0])] = decodeURIComponent(
item.split("=")[1]
);
});return result;
}export default {name: "LoginResult",props: {},
data() {return {OpenId1: "",OpenId2: ""
};
},
created() {var result = parseUrlParams();if (!(result && result.token)) {
alert("無效的登錄");return;
}var that = this;
axios({methods: "get",url: "https://localhost:5001/OpenId?provider=GitHub",headers: {Authorization: "Bearer " + result.token
}
}).then(function(response) {console.log(response);
that.OpenId1 = response.data;
});
axios({methods: "get",url: "https://localhost:5001/GetOpenIdByToken",headers: {Authorization: "Bearer " + result.token
}
}).then(function(response) {console.log(response);
that.OpenId2 = response.data;
});
}
};script>

前端運行

yarn install
yarn serve

點擊GitHub登錄,第一次,我們會跳到github的網站,然后登錄成功,重定向我們的后端,可以看到GetOpenIdByToken方法根據生成的token值,解析出了用戶id,這樣前端在login-result這個組件中,把token保存好,并重定向自己的主頁,獲取用戶所有信息即可。

data: 18613266
status: 200
config: {url: "https://localhost:5001/GetOpenIdByToken"}

OpenId?provider=GitHub則得不到數據,只能瀏覽器直接請求https://localhost:5001/OpenId?provider=GitHub,才能到github 的id。這個適應于前后端不分離,或者屬于之前我們經常使用MVC結構,同一域名下,同一端口,基于Cookies登錄的判斷。

參考

  • .net Core2.2 WebApi通過OAuth2.0實現微信登錄

  • AspNetCore3.0 和 JWT

  • 用戶系統設計:第三方授權、賬號綁定及解綁(下)

Demo 示例

  • GitHub?https://github.com/luoyunchong/dotnetcore-examples/blob/master/aspnetcore-oatuth2

總結

以上是生活随笔為你收集整理的aspnet登录界面代码_SPA+.NET Core3.1 GitHub第三方授权登录的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。