ASP.Net Core中JWT基本使用

JWT

授权

1.配置文件添加属性

 "Jwt": {
   "SecretKey": "SDMC-CJAS1-SAD-DFSFA-SADHJVF-VFAAAAAAA",
   "Issuer": "http://localhost:5200",
   "Audience": "http://localhost:5200"
 }

2.Program.cs中注册授权

 app.UseAuthentication(); // 必须在 UseAuthorization 之前
 app.UseAuthorization();

3.开始授权

 using Microsoft.AspNetCore.Mvc;
 using Microsoft.IdentityModel.Tokens;
 using System.IdentityModel.Tokens.Jwt;
 using System.Security.Claims;
 using System.Text;
 ​
 public class TestController : ControllerBase
 {
     // 注入 IConfiguration 服务,用于读取配置文件中的设置
     private readonly IConfiguration _configuration;
 ​
     // 构造函数,接收 IConfiguration 参数
     public TestController(IConfiguration configuration)
     {
         _configuration = configuration;
     }
 ​
     // 定义一个 HTTP GET 方法,返回一个 JWT 令牌
     [HttpGet]
     public string Get()
     {
         // 创建声明数组,包含用户的相关信息
         // 这里添加了用户 ID 和用户名的声明
         var claims = new Claim[]
         {
             new Claim("Id", "1"), // 用户 ID
             new Claim("UserName", "123") // 用户名
             // 注意:不要在声明中存储敏感信息
         };
 ​
         // 从配置文件中读取 JWT 设置
         var jwtSettings = _configuration.GetSection("Jwt");
 ​
         // 创建对称加密密钥,用于签名 JWT 令牌
         var key = new SymmetricSecurityKey(
             Encoding.UTF8.GetBytes(jwtSettings["SecretKey"])
         );
 ​
         // 创建 JWT 令牌
         var token = new JwtSecurityToken(
             issuer: jwtSettings["Issuer"], // 令牌的颁发者
             audience: jwtSettings["Audience"], // 令牌的受众
             claims: claims, // 令牌中的声明
             notBefore: DateTime.Now, // 令牌生效时间
             expires: DateTime.Now.AddHours(1), // 令牌过期时间(1 小时后)
             signingCredentials: new SigningCredentials(
                 key, // 签名密钥
                 SecurityAlgorithms.HmacSha256 // 签名算法
             )
         );
 ​
         // 使用 JwtSecurityTokenHandler 将令牌转换为字符串格式
         var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
 ​
         // 返回生成的 JWT 令牌
         return jwtToken;
     }
 }

鉴权

1.注册鉴权

program.cs

 // 从配置文件中获取 JWT 设置
 var jwtSettings = builder.Configuration.GetSection("Jwt");
 ​
 // 配置 JWT 身份验证
 builder.Services.AddAuthentication(options =>
 {
     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
 })
 .AddJwtBearer(options =>
 {
     options.TokenValidationParameters = new TokenValidationParameters
     {
         ValidateIssuer = true,
         ValidateAudience = true,
         ValidateLifetime = true,
         ValidateIssuerSigningKey = true,
         ValidIssuer = jwtSettings["Issuer"],
         ValidAudience = jwtSettings["Audience"],
         IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["SecretKey"]))
     };
 });

2.给要鉴权的类和方法上面加上[Authorize]

 [HttpGet]
 public string NoAuthorize()
 {
     return "this is NoAuthorize";
 }
 ​
 [Authorize]
 [HttpGet]
 public string Authorize()
 {
     return "this is Authorize";
 }

鉴权了的方法会报401

ASP.Net Core中JWT基本使用_第1张图片

swagger配置密钥

 c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
         {
           In=ParameterLocation.Header,
           Type=SecuritySchemeType.ApiKey,
           Description= "直接在下框中输入Bearer {token}(注意两者之间是一个空格)",
           Name="Authorization",
           BearerFormat="JWT",
           Scheme="Bearer"
         });
         c.AddSecurityRequirement(new OpenApiSecurityRequirement
         {
           {
             new OpenApiSecurityScheme
             {
               Reference=new OpenApiReference
               {
                 Type=ReferenceType.SecurityScheme,
                 Id="Bearer"
               }
             },
             new string[] {}
           }
         });

密钥格式(不能省略空格)

 Bearer xxxxxxxxxxxxxxx

你可能感兴趣的:(C#,asp.net,后端)