ToB企服应用市场:ToB评测及商务社交产业平台

标题: API身份认证JWT [打印本页]

作者: 雁过留声    时间: 2023-7-12 15:31
标题: API身份认证JWT
JWT简介

是一种身份认证的开放标准(RFC 7519),可以在网络应用间传输信息作为Json对象。由三部分组成:头部(Header)、载荷(payload)和签名(Signature).
头部(Header)

两部分组成,令牌类型和所使用的的签名算法
  1. {
  2. "alg":"HS256",
  3. "typ":"JWT"
  4. }
复制代码
 
载荷(payload)

包含要传输的信息,包括用户的身份信息、权限等。载荷可以自定义,但需要避免包含敏感信息。
  1. {
  2. "sub":"1234567890",
  3. "name":"zuozuo",
  4. "iat":17773219179
  5. }
复制代码
 
签名(Signature)

用于验证令牌的完整性和真实性,通常通过使用头部和载荷中的数据以及一个密钥进行加密生成
  1. HMACSHA256(
  2. base64UrlEncode(header)+"."+
  3. base64UrlEncode(payload),
  4. secret
  5. )
复制代码
 
JWT的工作流程




  1. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  2.     .AddJwtBearer(options =>
  3.     {
  4.         options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
  5.         {
  6.             ValidateIssuer = true,
  7.             ValidateAudience = true,
  8.             ValidateLifetime = true,
  9.             ValidateIssuerSigningKey = true,
  10.             ValidIssuer = "NetCoreDemo",
  11.             ValidAudience = "Test",
  12.             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("!Qq123456Test*"))
  13.         };
  14.     });
复制代码
 
  1. app.UseAuthentication();
  2. app.UseAuthorization();
复制代码
 

  1. [HttpPost]
  2.         public IActionResult Login(string username, string password)
  3.         {
  4.             if (username == "admin" && password == "admin")
  5.             {
  6.                 var tokenHandler = new JwtSecurityTokenHandler();
  7.                 var key = Encoding.UTF8.GetBytes("!Qq123456Test*dsadsadsadsadsa");//密钥
  8.                 var tokenDescriptor = new SecurityTokenDescriptor
  9.                 {
  10.                     Subject = new System.Security.Claims.ClaimsIdentity(
  11.                         new Claim[] {
  12.                             new Claim(ClaimTypes.Name, username)
  13.                         }),
  14.                     Expires = DateTime.UtcNow.AddHours(1),
  15.                     SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
  16.                 };
  17.                 var token = tokenHandler.CreateToken(tokenDescriptor);
  18.                 var tokenString = tokenHandler.WriteToken(token);
  19.                 return Ok(new { Token = tokenString });
  20.             }
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4