安装 Nuget包:
Microsoft.AspNetCore.Authentication.JwtBearer System.IdentityModel.Tokens.Jwt
2. 然后,配置JWT服务和认证:在 Program.cs 文件中
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System.Text; // 添加JWT验证 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidIssuer = "Issuer", //与签发token时的Issuer匹配 ValidAudience = "Audience",//与签发token时的Audience匹配 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("I4T0O/RW4zOfO42Hbv9jROUWfwr19LlVazJWkcHM3rc=")) //与签发token时的密钥匹配
}; });
builder.Services.AddControllers(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization();
3. 接下来,创建一个控制器来处理用户登录并生成token:
using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace Zhaoxi.Shopping.Admin.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class GetTokenController : ControllerBase { [HttpPost] public IActionResult Login(string username, string password) { // 验证用户身份,这里简化为直接通过 var secretKey = "I4T0O/RW4zOfO42Hbv9jROUWfwr19LlVazJWkcHM3rc="; var issuer = "Issuer"; var audience = "Audience"; var token = GenerateJwtToken(username, secretKey, issuer, audience); return Ok(new { token }); } private string GenerateJwtToken(string username, string secretKey, string issuer, string audience) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( issuer: issuer, audience: audience, claims: claims, expires: DateTime.Now.AddMinutes(30), // 设置token有效期 signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); } } }
secretKey 密钥可以使用 : 你可以使用C#的RNGCryptoServiceProvider
类来生成随机的字节数组,然后将其转换为Base64编码的字符串作为JWT的秘钥。
using System; using System.Security.Cryptography; namespace YourNamespace { public class JwtKeyGenerator { public static string GenerateJwtSecretKey(int keySize) { byte[] secretKeyBytes = new byte[keySize]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(secretKeyBytes); } return Convert.ToBase64String(secretKeyBytes); } public static void Main(string[] args) { // 生成256位(32字节)的随机秘钥 string secretKey = GenerateJwtSecretKey(32); Console.WriteLine("Generated JWT Secret Key:"); Console.WriteLine(secretKey); } } }
标签:string,JWT,生成,secretKey,token,new,var,using From: https://www.cnblogs.com/tlfe/p/18230656