jwt:头部(Header)、载荷(Payload)和标记(Signature)
头部:主要是规定生成token加密方式的类型和算法,
载荷:可以存储一些用户身份信息
标记:主要作用防篡改,验证令牌的真实性和完整性
引用jwt包
appsettings里:
//jwt秘钥
"Jwt": {
"SecretKey": "jiangjianhaotest123",
"Issuer": "Webapitest123",
"Audience": "Webapitest123"
}
Program里:
//添加jwt授权验证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//取出私钥
var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"]);
options.TokenValidationParameters = new TokenValidationParameters()
{
//验证发布者
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
//验证接收者
ValidateAudience = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
//验证是否过期
ValidateLifetime = true,
//验证私钥
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
});
登陆接口部分(登录控制器)
[HttpGet]
public async Task<IActionResult> Login(string username, string password)
{
var model = await user.Login(username, password);
int uid= model.Id;
//Header,选择签名算法
var signingAlogorithm = SecurityAlgorithms.HmacSha256;
//Payload,存放用户信息,下面我们放了一个用户id
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub,uid.ToString())
};
//Signature
//取出私钥并以utf8编码字节输出
var secretByte = Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"]);
//使用非对称算法对私钥进行加密
var signingKey = new SymmetricSecurityKey(secretByte);
//使用HmacSha256来验证加密后的私钥生成数字签名
var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
//生成Token
var Token = new JwtSecurityToken(
issuer: configuration["Jwt:Issuer"],//发布者
audience: configuration["Jwt:Audience"],//接收者
claims: claims,//存放用户信息
notBefore: DateTime.UtcNow,//发布时间
expires: DateTime.UtcNow.AddDays(1),//有效期设置一天
signingCredentials//数字签名
);
//生成字符串token
var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
return Ok(TokenStr);
}
vue部分:
axios.defaults.timeout = 8000000
axios.defaults.baseURL = "http://localhost:5244/api/"
//http request拦截器
axios.interceptors.request.use(
config => {
if (localStorage.Token) {//判断token是否存在
config.headers.Authorization = "Bearer " + localStorage.Token//将token设置成请求头
}
return config;
},
err => {
return Promise.reject(err);
}
);
//http response拦截器
axios.interceptors.response.use(
response => {
console.log(response.data)
if (response.data.errno === 999) {
router.replace('/')
console.log("token过期")
}
return response;
},
error => {
return Promise.reject(error);
}
);
export default axios;
标签:axios,return,JWT,Jwt,new,var,授权,response From: https://www.cnblogs.com/qibaidao/p/17615942.html