什麼是JWT
JWT (全稱:Json Web Token)是一個開放标準(RFC 7519),它定義了一種緊湊的、自包含的方式,用于作為 JSON 對象在各方之間安全地傳輸資訊。該資訊可以被驗證和信任,因為它是數字簽名的。
jwt和token差別
jwt和token差別主要展現在接收的資訊是否需要進入資料庫查詢資訊。
服務端驗證用戶端發來的token資訊要進行資料的查詢操作;而JWT驗證用戶端發來的token資訊不需要, JWT使用密鑰校驗不用資料庫的查詢。
.Net Core使用JWT
1、NUGET添加引用包
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
2、生成jwt字元串
public static string Loginjwt(long ID)
{
//引用System.IdentityModel.Tokens.Jwt
DateTime utcNow = DateTime.UtcNow;
SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));
var claims = new List<Claim>() {
new Claim("ID",ID.ToString()),
new Claim("Name","fan")
};
JwtSecurityToken jwtToken = new JwtSecurityToken(
issuer: "fan",
audience: "audi~~!",
claims: claims,
notBefore: utcNow,
expires: utcNow.AddYears(1),
signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
);
//生成token方式1
string jwtString = new JwtSecurityTokenHandler().WriteToken(jwtToken);
return jwtString;
}
3、對jwt進行校驗和解析
public static uint? Checkjwt(string jwtString)
{
SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));
//校驗token
var validateParameter = new TokenValidationParameters()
{
ValidateLifetime = true,
ValidateAudience = true,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "fan",
ValidAudience = "audi~~!",
IssuerSigningKey = securityKey,
};
try
{
//校驗并解析token
var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(jwtString, validateParameter, out SecurityToken validatedToken);//validatedToken:解密後的對象
var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //擷取payload中的資料
return Convert.ToUInt32(JsonHelper.GetObject<JwtRootobject>(jwtPayload).ID);
}
catch (SecurityTokenExpiredException)
{
//表示過期
throw new Exception("登入過期");
}
catch (SecurityTokenException)
{
//表示token錯誤
throw new Exception("token錯誤");
}
catch (Exception)
{
throw new Exception("驗證失敗");
}
//不校驗,直接解析token
//jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token1);
}
4、針對請求進行頭部驗證
Authorization
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request != && context.HttpContext.Request.Headers != && context.HttpContext.Request.Headers["Authorization"].Count > 0)
{
var token = context.HttpContext.Request.Headers["Authorization"];
if (string.IsOrWhiteSpace(token))
{
throw new CustomException("權限錯誤", ReturnCode.E1000004);
}
else
{
if (!Getusergraphql(token))
{
throw new CustomException("權限錯誤", ReturnCode.E1000004);
}
//GenericIdentity ci = new GenericIdentity(token);
//ci.Label = "conan1111111";
//context.HttpContext.User = new GenericPrincipal(ci, );
}
}
else
{
throw new CustomException("權限錯誤", ReturnCode.E1000004);
}
base.OnActionExecuting(context);
}
至此,我們完成了jwt的校驗流程。