JwtBearer

Nuget安装:Microsoft.AspNetCore.Authentication.JwtBearer

appsetting.json中添加配置项

    public class LoginController : ControllerBase
    {
        public IConfiguration Configuration { get; private set; }

        public LoginController(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    }

 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Jwt": {
    "Issuer": "",
    "Audience": "",
    "Expires": 10,
    "Security": "asdasdfasdfdlglasdkgj"
  }
}
 public static class TokenHelper
    {
        public static string CreateToken(JwtTokenModel jwtTokenModule)
        {
            var claims = new[]
            {
                new Claim("Id",jwtTokenModule.Id.ToString()),
                new Claim("CustomerNo",jwtTokenModule.CustomerNo),
                new Claim("CustomerName",jwtTokenModule.CustomerName)
            };
            //生成密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtTokenModule.Security));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: jwtTokenModule.Issuer,
                audience: jwtTokenModule.Audience,
                expires: DateTime.Now.AddMinutes(jwtTokenModule.Expires),
                claims: claims
                );
            var accessToken = new JwtSecurityTokenHandler().WriteToken(token);
            return accessToken;
        }
    }
        [HttpPost]
        public string GetToken(int customerId,string customerNo,string customerName)
        {

            var token = Configuration.GetSection("Jwt").Get<JwtTokenModel>();
            token.Id = customerId;
            token.CustomerNo = customerNo;
            token.CustomerName = customerName;
            return TokenHelper.CreateToken(token);
        }

 MD5加密类

    public static class MD5Helper
    {
        public static string ToMd5(this string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes = md5.ComputeHash(Encoding.Default.GetBytes(str + "@HolyAce"));
            var md5str = BitConverter.ToString(bytes).Replace("-", "");
            return md5str;
        }

    }
View Code

 

posted @ 2021-11-22 22:14  浩鑫  阅读(219)  评论(0)    收藏  举报