首先需要安装的NuGet包有:
Microsoft.AspNetCore.Authentication.JwtBearer
Swashbuckle.AspNetCore
Swashbuckle.AspNetCore.Filters
jose-jwt
大致是这些代码放到项目中如果有报错信息再去具体解决安装需要的NuGet包。
首先需要在Startup.cs文件中的ConfigureServices方法中添加的代码有
services.AddSwaggerGen(options =>
{
//开启权限锁
options.OperationFilter<AddResponseHeadersFilter>();
options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
options.OperationFilter<SecurityRequirementsOperationFilter>();
//在header中添加token,传递到后台
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) \"",
Name = "Authorization",//jwt默认的参数名称
In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type = SecuritySchemeType.ApiKey
});
});
//认证方案
services.AddAuthentication(option => {
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(
option => {
option.TokenValidationParameters = new TokenValidationParameters
{
//是否验证发行人
ValidateIssuer = true,
ValidIssuer = Configuration["JwtConfig:Issuer"],//发行人
//是否验证受众人
ValidateAudience = true,
ValidAudience = Configuration["JwtConfig:Audience"],//受众人
//是否验证密钥
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtConfig:key"])),
ValidateLifetime = true, //验证生命周期
RequireExpirationTime = true, //过期时间
ClockSkew = TimeSpan.Zero //平滑过期偏移时间
};
}
);
接着在Configure方法中开启两个中间件
//认证中间件
app.UseAuthentication();
//授权中间件
app.UseAuthorization();
然后在appsettings.json中加入以下配置
"JwtConfig": {
"key": "JWTStudyWebsite_DI20DXU3",
"Issuer": "testJwt",
"Audience": "wlw"
},
去使用一个简单的登录去测试JWT是否可以生成
/// <summary>
/// 登录
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
public async Task<ResultDto> LoginAsync(LoginDto dto)
{
//图片验证码对比
var captchaRul = _captcha.Validate(dto.id, dto.code);
if (!captchaRul)
{
return new ResultDto
{
Result = Result.Failure,
Message = "验证码错误,请重新输入"
};
}
else
{
var uData = await _baseRepository.FindAsync(x => x.UserName == dto.UserName);
if (uData == null)
{
return new ResultDto
{
Result = Result.Failure,
Message = "未找到此用户!"
};
}
else if (uData.Password.ToUpper() == dto.Password.Md5().ToUpper())
{
var roleIds = _baseadminRoleResRepository.Queryable().Where(x => x.AdminId == uData.AdminId).Select(m => m.RoleId).ToList();
//身份信息认证
//Session或Cookies换成JWT
IList<Claim> claims = new List<Claim> {
new Claim(JwtClaimTypes.Id,uData.AdminId.ToString()),
new Claim(JwtClaimTypes.Name,uData.UserName),
new Claim(ClaimTypes.Name,uData.UserName),
new Claim(ClaimTypes.Role,string.Join(',',roleIds))
};
//JWT密钥
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:key"]));
//算法
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//过期时间
DateTime expires = DateTime.UtcNow.AddMinutes(30);
//Payload负载
var token = new JwtSecurityToken(
issuer: configuration["JwtConfig:Issuer"],
audience: configuration["JwtConfig:Audience"],
claims: claims,
notBefore: DateTime.UtcNow,
expires: expires,
signingCredentials: cred
);
var handler = new JwtSecurityTokenHandler();
//生成令牌
string jwt = handler.WriteToken(token);
return new ResultDto
{
Result = Result.Success,
Message = "登录成功",
Token = jwt,
};
}
else
{
return new ResultDto
{
Result = Result.Failure,
Message = "密码错误!"
};
}
}
}
如果代码中的有报错的地方是需要引用一个NuGet包:IdentityModel
最后就可以生成Token了。