1.下载Nuget包(与你.NET 版本一致的版本)
Microsoft.AspNetCore.Authentication.JwtBearer
2.在appsetting.json中配置jwt
点击查看代码
"JwtConfig": {
"SecretKey": "123123123123", // 密钥 可以是guid 也可以是随便一个字符串
"Issuer": "zhangsan", // 颁发者
"Audience": "zhangsan", // 接收者
"Expired": 30 // 过期时间(30min)
},
3.配置JwtConfig类
点击查看代码
public class JwtConfig : IOptions<JwtConfig>
{
public JwtConfig Value => this;
public string SecretKey { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public int Expired { get; set; }
public DateTime NotBefore => DateTime.UtcNow;
public DateTime IssuedAt => DateTime.UtcNow;
public DateTime Expiration => IssuedAt.AddMinutes(Expired);
private SecurityKey SigningKey => new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
public SigningCredentials SigningCredentials =>
new SigningCredentials(SigningKey, SecurityAlgorithms.HmacSha256);
}
4.创建生成jwt的工具类
点击查看代码
public class GenerateJwt
{
private readonly JwtConfig _jwtConfig;
public GenerateJwt(IOptions<JwtConfig> jwtConfig)
{
_jwtConfig = jwtConfig.Value;
}
/// <summary>
/// 生成token
/// </summary>
/// <param name="sub"></param>
/// <param name="customClaims">携带的用户信息</param>
/// <returns></returns>
public JwtTokenResult GenerateEncodedTokenAsync(string sub, LoginUserModel customClaims)
{
//创建用户身份标识,可按需要添加更多信息
var claims = new List<Claim>
{
new Claim("userid", customClaims.userid),
new Claim("username", customClaims.username),
//new Claim("realname",customClaims.realname),
//new Claim("roles", string.Join(";",customClaims.roles)),
//new Claim("permissions", string.Join(";",customClaims.permissions)),
//new Claim("normalPermissions", string.Join(";",customClaims.normalPermissions)),
new Claim(JwtRegisteredClaimNames.Sub, sub),
};
//创建令牌
var jwt = new JwtSecurityToken(
issuer: _jwtConfig.Issuer,
audience: _jwtConfig.Audience,
claims: claims,
notBefore: _jwtConfig.NotBefore,
expires: _jwtConfig.Expiration,
signingCredentials: _jwtConfig.SigningCredentials);
string access_token = new JwtSecurityTokenHandler().WriteToken(jwt);
return new JwtTokenResult()
{
access_token = access_token,
expires_in = _jwtConfig.Expired * 60,
token_type = JwtBearerDefaults.AuthenticationScheme,
user = customClaims
};
}
}
5.定义模型
点击查看代码
/// 登录成功返回model
/// </summary>
public class JwtTokenResult
{
public string access_token { get; set; }
public string refresh_token { get; set; }
/// <summary>
/// 过期时间(单位秒)
/// </summary>
public int expires_in { get; set; }
public string token_type { get; set; }
public LoginUserModel user { get; set; }
}
public class LoginUserModel
{
public string userid { get; set; }
public string username { get; set; }
public string realname { get; set; }
public string roles { get; set; }
public string permissions { get; set; }
public string normalPermissions { get; set; }
}
6.Startup配置
点击查看代码
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using WebJWT;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//注入jwt
builder.Services.AddScoped<GenerateJwt>();
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection("JwtConfig"));
#region jwt验证
var jwtConfig = new JwtConfig();
builder.Configuration.Bind("JwtConfig", jwtConfig);
builder.Services
.AddAuthentication(option =>
{
//认证middleware配置
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
//Token颁发机构
ValidIssuer = jwtConfig.Issuer,
//颁发给谁
ValidAudience = jwtConfig.Audience,
//这里的key要进行加密
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.SecretKey)),
//是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
ValidateLifetime = true,
};
});
#endregion
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();//要在授权之前认证
app.UseAuthorization();
app.MapControllers();
app.Run();
7.调用获取token
控制器代码如下:
点击查看代码
[Route("api/[controller]/[action]")]
[ApiController]
public class TestController : Controller
{
private readonly GenerateJwt _generateJwt;
public TestController(GenerateJwt generate) {
this._generateJwt = generate;
}
[HttpGet]
public ActionResult GetLogin(string name,string userid) {
var claims = new LoginUserModel()
{
userid = userid,
username = name,
realname = name,
//roles = string.Join(";", user.roles),
//permissions = string.Join(";", user.permissions),
};
var refreshToken = Guid.NewGuid().ToString();
//当然 你要在生成token之前要验证一下账户是否在数据库存在 存在则生成
/*
数据库查询
*/
var jwtTokenResult = _generateJwt.GenerateEncodedTokenAsync(userid, claims);
jwtTokenResult.refresh_token = refreshToken;
return Json(jwtTokenResult);//这里可按需返回 如果不想返回用户信息 比如密码 可以在_generateJwt.GenerateEncodedTokenAsync去掉哦
}
}
8.测试一下发现成功即可,SwaggerUI添加认证
点击查看代码
builder.Services.AddSwaggerGen(options =>
{
#region 启用swagger验证功能
//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称一致即可。
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer",
});
#endregion 启用swagger验证功能
});