asp.net?core?中的Jwt(Json?Web?Token)的使用详解(.net core jwt刷新token)没想到

随心笔谈1年前 (2023)发布 admin
121 0

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace aspnetcore013.Controllers
{
[Route(“api/[controller]/[action]”)]
[ApiController]
public class Test3Controller : ControllerBase
{
//用于 依赖注入
private readonly IOptionsSnapshot<JWTSetting> _settings;

//注入 设置
public Test3Controller(IOptionsSnapshot<JWTSetting> settings)
{
_settings=settings;
}

[HttpGet]
public ActionResult<string> Login(string userName,string passWord)
{
if(userName==”zhangsan”&& passWord==”123456″)
{
//这里已经 表明 登录 成功
//Claim为 JWT第二阶段的 payload
List<Claim> claims=new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, “66”));
claims.Add(new Claim(ClaimTypes.Name, “zhangsan”));
claims.Add(new Claim(“Wechat”, “jiujiu56”));//自定义 type名称
claims.Add(new Claim(ClaimTypes.Role, “admin”));
//下面为生成 JWT
string configkey=_settings.Value.Key;
DateTime outTime=DateTime.Now.AddSeconds(_settings.Value.OutTime);
byte[] byteKey=Encoding.UTF8.GetBytes(configkey);
var securityKey=new SymmetricSecurityKey(byteKey);
var credentials=new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
//设置 JWT第二阶段的 payload 和过期 时间 和 效验算法
var securityToken=new JwtSecurityToken(claims: claims, expires: outTime, signingCredentials: credentials);
string jwt=new JwtSecurityTokenHandler().WriteToken(securityToken);
return jwt;
}
else
{
return BadRequest(“登录失败”);
}
}
}
}

© 版权声明

相关文章