core Webapi jwt 认证
Web API Jwt
》》》》用户信息
namespace WebAPI001.Coms
{
public class Account
{
public string UserName { get; set; }
public string UserPassword { get; set; }
public string UserRole { get; set; }
}
}
》》》获取jwt类
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
namespace WebAPI001.Coms
{
public class JwtHelper
{
public static string GenerateJWT(Account user, IConfiguration _configuration)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(_configuration?.GetValue<string>("TokenParameter:Secret"));
var securityKey = new SymmetricSecurityKey(keyBytes);
// 创建JWT的签名凭证
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
// 设置JWT的Claims
var claims = new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.Role, user.UserRole),
// 添加其他需要的声明
};
// 创建JWT的Token
var token = new JwtSecurityToken(
issuer: _configuration.GetValue<string>("TokenParameter:Issuer"),
audience: _configuration.GetValue<string>("TokenParameter:Audience"),
claims: claims,
expires: DateTime.Now.AddMinutes(_configuration.GetValue<int>("TokenParameter:AccessExpiration")),
signingCredentials: signingCredentials
);
// 生成JWT字符串
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return jwtToken;
}
}
}
// Core 自带官方 JWT认证
// 开启Bearer 认证
builder.Services.AddAuthentication(options =>
{
// 设置默认的身份验证和挑战方案为 JwtBearer
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}) // 配置 JWT Bearer 选项
.AddJwtBearer(options =>
{
// 配置 Token 验证参数
options.TokenValidationParameters = new TokenValidationParameters
{
// 验证发行者
ValidateIssuer = true,
// 验证受众
ValidateAudience = true,
// 验证令牌有效期
ValidateLifetime = true,
// 验证签名密钥
ValidateIssuerSigningKey = true,
// 发行者
ValidIssuer = builder.Configuration["TokenParameter:Issuer"],
// 受众
ValidAudience = builder.Configuration["JokenParameter:Audience"],
// 签名密钥
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["TokenParameter:Secret"])),
AudienceValidator = (m, n, z) => {
//自定义验证逻辑
return true;
}
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
// 如果过期,则把 是否过期 添加到 , 返回头信息中
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
//OnForbidden
//OnChallenge
//OnMessageReceived
//OnTokenValidated
};
});
原文地址:https://blog.csdn.net/u013400314/article/details/144272117
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!