当前位置:网站首页>【AspNetCore】实现JWT(使用Microsoft.AspNetCore.Authentication.JwtBearer)
【AspNetCore】实现JWT(使用Microsoft.AspNetCore.Authentication.JwtBearer)
2022-08-09 02:05:00 【又被平均了】
概述
在AspNetCore 中实现Jwt比较简单,使用Microsoft.AspNetCore.Authentication.JwtBearer 库,再加几行代码即可.
步骤(2.x/3.x通用)
- 新建一个AspNetCore WebApi项目.
- 创建获取token的方法
public static class JwtHelper
{
public static string GeneratorToken(string username)
{
// 服务端密钥 一般16bit 以上
var secret = "1234567890123456";
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
// 加密算法
var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
// 自定义claims
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name,username)
};
var token = new JwtSecurityToken(
"issuer", // 发行者
"audience", // 使用者
claims,
expires: DateTime.Now.AddMinutes(60),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
- 新建一个token控制器
public class TokenRequest
{
public string UserName {
get; set; }
public string Password {
get; set; }
}
[ApiController]
[Route("[controller]")]
public class TokenController:ControllerBase
{
[HttpPost("")]
public async Task<IActionResult> GetToken([FromBody]TokenRequest request)
{
// 验证用户名密码
var token = JwtHelper.GeneratorToken(request.UserName);
return Ok(token);
}
}
- Startup 注册和启用中间件
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(
JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["access_token"];
return Task.CompletedTask;
}
};
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "issuer",
ValidAudience = "audience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890123456"))
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
- 验证获取token

- 验证api(使用Authorize过滤器)
没有token时
带上token时
说明
使用 验证如下
- 加密后的jwt token 包含三个部分,分别是包含源数据说明的HEADER、包含自定义声明信息的PAYLOAD、以及用于验证的签名签名信息 SIGNATURE
- 在分布式生产环境中,api 和token server 分别维护各自的公钥.
边栏推荐
猜你喜欢
随机推荐
typescript90-使用类型文件声明类型
Which is the best increased whole life insurance?Is it really safe?
德语翻译器在线翻译中文
帮助安全红队取得成功的11条建议
.reduce()的简单例子
嵌入式设备驱动开发
【Unity】判断鼠标是否点击在UI上
MT4/MQ4L入门到精通EA教程第二课-MQL语言常用函数(二)-账户信息常用功能函数
HNUMSC-C语言第一课
【HNUMSC】C language second lecture
How js implements array deduplication (7 kinds)
eladmin container deployment super detailed process
企业从云服务的承诺支出中获得最大收益的四种方法
New Swagger3.0 tutorial, OAS3 quick configuration guide, to automate API interface documentation!
中国SSD产业突围有多难?除了技术“瓶颈”还有哪里挑战?
The first lesson of HNUMSC-C language
Analysis of when AuthenticationSuccessHandler is called after UsernameAuthenticationFilter is authorized successfully
How to install ngrok in Synology system (Synology 6.X version)
9.1-----24. Swap the nodes in the linked list in pairs
2022 PMP Project Management Certification Exam Registration Guide (1)









