1、安装组件(Nuget)
Microsoft.AspNetCore.Authentication.JwtBearer
2、Program.cs 配置
//授权认证(使用JWT)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
// 私钥
var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
// 验证发布者
ValidateIssuer = true,
// 发布者信息
ValidIssuer = "BeiJingBW",
// 验证接收者
ValidateAudience = true,
// 接收者
ValidAudience = "BeiJingBW",
// 验证是否过期
ValidateLifetime = true,
// 验证私钥
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
});
// 配置Swagger
builder.Services.AddSwaggerGen(o =>
{
// 显示 授权信息
o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
{
Description = "添加JWT授权Token:Bearer Token值",
Name = "Authorization",
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[]
{
}
}
});
});
// 鉴权
app.UseAuthentication();
app.UseAuthorization();
3、控制器加授权认证 [Authorize],登录判定方法设置为匿名可访问 [AllowAnonymous]
[Route("api/[controller]/[action]")] // 路由配置
[ApiController]
[Authorize]
public class ECommerceController : ControllerBase
{
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string? loginName, string? password)
{
// 登录判定
}
}
4、控制器中,编写生成 JWT Token 方法
/// <summary>
/// 生成 JWT Token(令牌)
/// </summary>
/// <returns></returns>
private string CreateTokenString()
{
//私钥
var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
// 非对称加密
var signingKey = new SymmetricSecurityKey(secretByte);
// 使用256 生成数字签名
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
// 生成Token
var token = new JwtSecurityToken(
issuer: "BeiJingBW",
audience: "BeiJingBW",
expires: DateTime.Now.AddDays(1), // 一天后过期
signingCredentials: signingCredentials
);
// 生成token 字符串
var strToken = new JwtSecurityTokenHandler().WriteToken(token);
return strToken;
}
5、登录方法中,登录成功要生成 JWT Token,返回给前端
/// <summary>
/// 登录判定(可以匿名,也就是授权对它没有作业)
/// </summary>
/// <param name="loginName">登录名</param>
/// <param name="password">密码</param>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string? loginName, string? password)
{
try
{
// 登录判定,登录成功
// 登录成功生成JWT Token
string strToken = this.CreateTokenString();
}
// 返回前端信息加Jwt token信息
return Ok(new
{
user = user,
token = strToken
});
}
catch (Exception ex)
{
// 错误日志
logger.LogError("登录判定出错!" + ex.Message);
throw;
}
}
6、Swagger中调试
- 运行登录方法,复制生成的 JWT token字符串。
- 点击 名上角 “Authorize” 按钮,在文本框中输入:Bearer token值,格式如:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODYyOTc3NTgsImlzcyI6IkJlaUppbmdCVyIsImF1ZCI6IkJlaUppbmdCVyJ9.hb9kZv_qj8Eosgnw6ayTf6nA2-07ym6p6xbVS237aI8,点击“Authorize”。
- 之后运行Swagger中的其它方法,它会自动加载 JWT token,方法正常运行。如果没有第2部,运行方法会提示无授权的错误。
7、前端Vue配置
7.1 main.js 配置
// 数据访问
import axios from 'axios'
// 添加JWT token信息
axios.defaults.headers.common["Authorization"] = "Bearer " + window.localStorage.getItem("token");
7.2 登录方法,成功登录后,写token信息到本地
methods:{
// 登录
login() {
// 登录判定
// 登录成功,写JWT的 token到本地
window.localStorage.setItem("token", res.data.token);
// 数据提交后端要加入新的Token值
this.axios.defaults.headers.common["Authorization"] =
"Bearer " + res.data.token;
}
}
标签:Bearer,登录,JWT,Token,token,new
From: https://www.cnblogs.com/Beijingqq/p/17657987.html