一、项目>管理Nuget包 安装 二、.appsettings.JSON添加 "Jwt": { "Secret": "~!@#$%^&*()_+qwert
"Jwt": {
"Secret": "~!@#$%^&*()_+qwertyuiopasldkh[o51485421ajshk^%*)kasd", // 密钥
"Issuer": "kfjdhf", // 颁发者
"Audience": "kfjdhf", // 接收者
//"Expired": 30 // 过期时间(30min)
}
#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
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);
}
}
}
/// 登录
/// </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();
}
--结束END--
本文标题: .net core api接口JWT方式认证Token
本文链接: https://lsjlt.com/news/159741.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-05-21
2023-05-21
2023-05-21
2023-05-21
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0