一、项目>管理Nuget包 安装
二、.appsettings.json添加
"JWT": {
"Secret": "~!@#$%^&*()_+qwertyuiopasldkh[o51485421ajshk^%*)kasd", // 密钥
"Issuer": "kfjdhf", // 颁发者
"Audience": "kfjdhf", // 接收者
//"Expired": 30 // 过期时间(30min)
}
三、ConfigureServices注入jwt
#region 注册JWT
//获取配置文件
var JWTConfig = Configuration.GetSection("JWT");
//生成密钥
var symmetricKeyAsBase64 = JWTConfig.GetValue<string>("Secret");
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
//认证参数
services.AddAuthentication("Bearer")
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,//是否验证签名,不验证的画可以篡改数据,不安全
IssuerSigningKey = signingKey,//解密的密钥
ValidateIssuer = true,//是否验证发行人,就是验证载荷中的Iss是否对应ValidIssuer参数
ValidIssuer = JWTConfig.GetValue<string>("Iss"),//发行人
ValidateAudience = true,//是否验证订阅人,就是验证载荷中的Aud是否对应ValidAudience参数
ValidAudience = JWTConfig.GetValue<string>("Aud"),//订阅人
ValidateLifetime = true,//是否验证过期时间,过期了就拒绝访问
ClockSkew = TimeSpan.Zero,//这个是缓冲过期时间,也就是说,即使我们配置了过期时间,这里也要考虑进去,过期时间+缓冲,默认好像是7分钟,你可以直接设置为0
RequireExpirationTime = true,
};
});
#endregion
(2).Configure启用
app.UseAuthentication();//jwt
四、创建jwt帮助类
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
namespace SystemAPi.JWT
{
public class JwtHelper
{
public JwtHelper(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 配置属性
/// </summary>
public IConfiguration Configuration { get; }
/// <summary>
/// 生成Token
/// </summary>
/// <returns></returns>
public string GenerateToken(List<Claim> claims)
{
var jwtConfig = Configuration.GetSection("Jwt");
//秘钥,就是标头,这里用Hmacsha256算法,需要256bit的密钥
var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.GetValue<string>("Secret"))), SecurityAlgorithms.HmacSha256);
//Claim,JwtRegisteredClaimNames中预定义了好多种默认的参数名,也可以像下面的Guid一样自己定义键名.
//ClaimTypes也预定义了好多类型如role、email、name。Role用于赋予权限,不同的角色可以访问不同的接口
//相当于有效载荷
List<Claim> baseClaims = new List<Claim>{
new Claim(JwtRegisteredClaimNames.Iss,jwtConfig.GetValue<string>("Issuer")),
new Claim(JwtRegisteredClaimNames.Aud,jwtConfig.GetValue<string>("Audience")),
new Claim("Guid",Guid.NewGuid().ToString("D")),
new Claim(ClaimTypes.Role,"admin"),
};
claims = claims.Union<Claim>(baseClaims).ToList<Claim>();//合并Claim,删除重复项目
SecurityToken securityToken = new JwtSecurityToken(
signingCredentials: securityKey,
expires: DateTime.Now.AddDays(1),//过期时间
claims: claims
);
//生成jwt令牌
return new JwtSecurityTokenHandler().WriteToken(securityToken);
}
}
}
五、测试登录成功把账户信息存进token
/// 登录
/// </summary>
/// <returns>登录</returns>
[HttpGet]
public ReturnJson login(string name, string pwd)
{
User data = bll.login(name, pwd);
if (data!=null)
{
if (data.name == name && data.password == pwd)
{
List<Claim> claims = new List<Claim>() {
new Claim(ClaimTypes.NameIdentifier, data.name),
new Claim(ClaimTypes.Role,data.AdminId.ToString()),
new Claim("AdminRole",data.AdminId.ToString())
};
string token=jwtHelper.GenerateToken(claims);
return new ReturnJson<string>().Success(token);
};
}
return new ReturnJson().Fail();
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。