
地 址:上海市楊浦66號
電 話(huà):15397061867
網(wǎng)址:www.fxyjd.com
郵 箱:[email protected]
這ヽ(′▽?zhuān)?/篇文章主要介紹了ASP.NET Core使用JWT認證授權的使用方法,文(wen)中通過(guò)示例代碼介紹的非常詳細,對大家的證授學(xué)習或者工作具有一定(ding)的參考學(xué)習價(jià)??值,需要的使用朋友們下面隨著(zhù)小編來(lái)一起學(xué)習學(xué)習吧
demo地址: https://github.com/william0705/JWTS
名詞解析
認證 : 識別用戶(hù)是否合法
授權: 賦予用戶(hù)權限 (能訪(fǎng)問(wèn)哪些資源)
鑒權: 鑒定權限是否合法
優(yōu)勢
1、 無(wú)狀態(tài)
token 存儲身份驗證所有信息 ,證授 服務(wù)端不需要保存用戶(hù)身份驗證信息, 減少服務(wù)端壓力 , 服務(wù)端更容易水平擴展, 由于無(wú)狀態(tài), 又會(huì )導致它最大缺點(diǎn) , 很難注銷(xiāo)
2、 支持跨域訪(fǎng)問(wèn)
Cookie是使用不允許垮域訪(fǎng)問(wèn)的,token支??持
3、證授 跨語(yǔ)言
基于標準化的使用 JSON Web Token (JWT) , 不依賴(lài)特定某一個(gè)語(yǔ)言 , 例如生成的Token可以對多種語(yǔ)言使用(Net , Java , PHP …)
劣勢
1、Token有效性問(wèn)題
后臺很難注銷(xiāo)已經(jīng)發(fā)布的證授Token , 通常需要借助第三方儲存(數據庫/緩存) 實(shí)現注銷(xiāo), 這樣就會(huì )失去JW??T最大的優(yōu)勢
2、占帶寬
Token長(cháng)度(取決存放內容) 比session_id??大 ,使用 每次請求多消耗帶寬 , token只存必要信息 , 避免token過(guò)長(cháng)
3、需要實(shí)現續簽
cookies – session 通常是證授框架已經(jīng)實(shí)現續簽功能, 每次訪(fǎng)問(wèn)把過(guò)期時(shí)間更新, JWT需要自己實(shí)現, 參考OAuth2刷新Token機制實(shí)現刷新Token
4、消耗更多CPU
每次請求需要對內容解密和驗證簽名這兩步操作,使用典型用時(shí)間換空間
只能根據自身使用場(chǎng)景決定使用哪一種身份驗證方案 ,證ヾ(′▽?zhuān)??授 沒(méi)有一種方案是通用的,完美的
.NET Core集成JWT認證授??權服務(wù)
1、證授引入nuget包,使用(yong)Syst(′?_?`)em.IdentityModel.Tokens.Jwt
2、創(chuàng )建生成Token的服務(wù),建議使用面向接口和實(shí)現編程???,方便服務(wù)注入容器(qi)ServicesCollection(涉及DI和IOC概念)
namespace JWTS.Services
{
public interface IJWTServ(′?ω?`)ice
{
/// <summary>
/// 根據驗證通過(guò)后的用戶(hù)以及角色生成Token,以達到角色控制(zhi)的作用
/// </summary>
/// <param name='userName'></param>
/// <param name="role"></param>
/// <returns></returns>
string GetToken(string userName,string role);
}
}
4、在appsettings.con??fig中添加生成t(╯°□°)╯︵ ┻━┻oken需要的信息,并映射成對象
"TokenParameter": {
"Issuer": "William", //這個(gè)JWT的簽發(fā)主體(發(fā)行者)
"Audience": "William", //這個(gè)JWT的接收對象
"SecurityKey": "askalsnlkndhasnaslkasmadka"
}
public class TokenParameter
{
public string Iss(╯‵□′)╯uer?? { get; set; }
public string Audience { get; set; }
public string SecurityKey { get; set;?? }
}
5、實(shí)現接口,注入Configuration,獲取Tokeヽ(′▽?zhuān)?ノnParameter對象
using??? Microsoft.Extensions.Configuration;
using System;
using System.IdentityModelヽ(′ー`)ノ.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace JWTS.Services
{
public class JWTService : IJWTService
{
private readonly='readonly' TokenParameter _tokenParameter;
public JWTService((′▽?zhuān)?ICon??figuration configuration)
{
_tokenParameter = configuration.GetSection("TokenParameter").??Get<TokenParameter>();
}
/// <summary>
/// JWT由三部分組成(Header、Payload、Signature)
/// { Head??er}.{ Payload}.{ Signat??ure}
/// </summary>
/// <par??am name="userName"></param>
//??/ <param name="role"></param>
/// <returns></returns>ヾ(^-^)ノ
public str??ing GetToken(str??ing userNa??me,string role)
{
Claim[] claims = new[]
{
new Claiヽ(′▽?zhuān)?ノm(ClaimTypes.Name, userName),
new Claim("NickNa??me","Richard"),
new Claim("Role",role)//傳遞其他信息
};
SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParame??ter.Securi??tyKey));
Signi??ngCredentials creds = new SigningCredent??ials(key, SecurityAlgorithms.HmacSha256);
/**
* Claims (Payload)
Claims 部分包含了一些跟這個(gè) token 有關(guān)的重要信息。 JWT 標準規定了一些字段,下面節選一些字段:
JWT會(huì )被加密,但是這部分內容任何人都可以讀取,所以不要存放機密信息
iss: The iss??uer of the token,tok(╯‵□′)╯en 是給誰(shuí)的
sub: The subject of th??e token( ?ω?),token?? 主題
exp: Expiration Time。 token 過(guò)期時(shí)間,Unix 時(shí)間戳格式
iat: Issued At。 token 創(chuàng )建時(shí)間??, Unix 時(shí)間戳格式
jti: JWT ID。針對當前 token 的唯一標識
除了規定的字段外,可以包含其他任何 JSON 兼容的字段。
* */
var?? token = new JwtSecurityToken(
issuer: _tokenParameter.Issuer,
audience: _tokenParameter.Audience,
claims: claims,
expires: DateTime.Now(′?ω?`).AddMinutes(10),//10分鐘有效期
sig(O_O)ningCredentials: creds);
string returnToken = new JwtSecurityT??okenHandler().WriteToヽ(′ー`)ノken(token);
return returnToken;
}
}
}
6、jwt中定義好的Claims
JWT標準里面定好的claim有:
iss(???Issuser):代表這個(gè)JWT的簽發(fā)主體;
sub(Subject):代表這個(gè)JWT的主體,即它的所有人;
exp(Expiration time):是一個(gè)時(shí)間戳,代表這個(gè)JWT的過(guò)期時(shí)間;
nbf(Not Before):是一個(gè)時(shí)間戳,代表這個(gè)JWT生效的開(kāi)??始時(shí)間,意味著(zhù)在這個(gè)時(shí)間之前驗證JWT是會(huì )失敗的;
iat(Issue(′?`)d at):是一個(gè)時(shí)間戳,代表這個(gè)JWT的簽發(fā)時(shí)間;
jti??(JWT ID):是JWT的唯一標識。
7、在鑒權項目工程Startup.cs文件里依賴(lài)注入JWT的服務(wù)類(lèi)
public void ConfigureServices(IServiceCollection servi??ces) { services.AddScoped <IJWTService, JWTService> (); services.Addヽ(′ー`)ノControllers(); }
8、添加AuthenticationController,生成Token,后期可以添加RefreshToken
using JWTS.Services;
usin??g Micヽ(′ー`)ノrosoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace JWTS.Controller??s
{
[Route("api/[controller]")]
[A??piController]
public class AuthenticationController : ControllerBase
{
#region 構造函數
private ILogger<AuthenticationController> _logger;
private IJWTServi??ce _iJWTService(′ω`);
private readonly IConfig??uration _iConfiguration;
public Authenticatioヾ(′ω`)?nController(ILogger&??lt;AuthenticationController> logger,
IConfiguration configuration
, IJWTService service)
{
_logger = logger;
_iConfiguration = conf(╯°□°)╯i?guration;
_iJWTService = service;
}
#endregion
/// <summary>
/// 實(shí)際場(chǎng)景使用Post方ヽ(′▽?zhuān)?ノ法??
///http://localhost:5000/api/Authentica??tion/Login?n??ame=william??&password=1231??23
///(′?_?`) </summary>
/// <param name='name'></pa(/ω\)ram>
/// <param name='password'></p??aram>
/// <returns></returns>
[Route("Login")]
[HttpGet]
public IActionResult Login(string nam??e, string password)
{
//這里應該是(′▽?zhuān)?需要去連接數據庫做數據校驗,為了方便所有用戶(hù)名和密碼(???)寫(xiě)死了
if ("william".Equals(name) && "123123".Equals(password))//應該數據庫
{
var role='Admini(╬?益?)str(???)ator';//可以從數據庫獲取角色
stヽ(′ー`)ノring token = this._iJWTService.GetToken(name, role);
return new JsonReヽ(′▽?zhuān)?ノsult(new
{
result = true,
token
});
}
return Unauthorized("Not Register!!!");
}
}
}
2、資源中心??API(⊙_⊙):使用從認證服務(wù)中心獲取的Token,去訪(fǎng)問(wèn)資源,資源中心對用戶(hù)信息以及Token進(jìn)行鑒權操作,認證失敗返回401
1、資源中心(xin)添加Nuget包(Microsoft.AspNetCore.Authen??tication.JwtBearer)
2、添加Auヽ(′▽?zhuān)?ノthentication服務(wù),添加JwtBearer(╯°□°)╯︵ ┻━┻,通過(guò)Configuration獲取TokenParameter對象
using Sy(T_T)stem;
using System.Text;
using API.Core.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Mic?rosoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.??Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
namespace API.Core
{
public class Startup
{
private TokenParameter _tokenParameter;
public IConfiguration Config??uration { ge(⊙_⊙)t;?? }
public Startu(′?`)p(IConfigur??(?_?;)ation configuration)
{
Configuration = config???uration;
_tokenParam??eter = co??nfiguration.GetSection("TokenPa??rameter").Get<TokenParameter>()??throw new ArgumentNullException(nameof(_tokenParameter));
}
public void ConfigureServic??es(IServiceCollection servic??es)
{
services.Add(′ω`*)Controllers();
servi(⊙_⊙)ces.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//默認授權機制
.AddJwtBearer(options =>
{
options.TokenValidationParam??eters=new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
Vali(′▽?zhuān)?)dateLifetime = true,
Va??lidateIssuerSigningKey = tru??e,
ValidIssuer = _tokenParam?eter.Issuer,
Valid??Audience = _tokenParameter.Audience,
IssuerSigningKey = new SymmetricS(′ω`)ecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.SecurityKey))
};
});
}
public void Configur(◎_◎;)e(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDe??veloperExceptionPage();
}
app.U(╬?益?)seRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoi(?Д?)nts =>
{
endpoints.MapControllers();
});
}
}
}
3、在資源控制器上添加[Authorize]屬性,以啟用認證授權訪(fǎng)問(wèn)API資源
[ApiController]
[Route("[controller](′?_?`)")]
[Authorize??]
public class WeatherForeヾ(′▽?zhuān)??castController : Contr(′;ω;`)ollerBase
{
private static readonly="" string[] Summaries = new[]
{
"F( ???)reezing", "Bracing", "Chilly", "Cool", "M??ild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public WeatherForecastController(ILogger<WeatherForecastControll(′?`)er&g(′?ω?`)t; logger)
{
_logger = logger;
}
[HttpGet]
public IEnume??rable<WeatherFor?ec(?⊿?)ast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
Temperatu(′▽?zhuān)?reC = rng.Next(-20, 55),
Summary = Summari(′Д` )es[rng.Next(Summaries.Length)]
})
.ToArr??ay();
}
}
到此這篇關(guān)ヽ(′▽?zhuān)?ノ于A(yíng)SP.NET Core使用JWT認證授權的方法的文章就介紹到這了,更多相關(guān)ASP.NET Core JWT認證授權 內容請搜索腳本之家以前的文章或??繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
來(lái)源:腳本之家
鏈接:https:/??/www.jb51.net/article/*.htm