Bootstrap

.net6 webapi使用JWT授权认证

1、引入包:Microsoft.AspNetCore.Authentication.JwtBearer
在这里插入图片描述
2、programe.cs

builder.Services.AddSwaggerGen();

//Jwt授权认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration["JWT:Issuer"],
        ValidateAudience = true,
        ValidAudience = builder.Configuration["JWT:Audience"],
        ValidateLifetime = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"]))
    };
    options.Events = new JwtBearerEvents
    {
        //此处为权限验证失败后触发的事件
        OnChallenge = context =>
        {
            //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
            context.HandleResponse();
            //自定义自己想要返回的结果
            var payload = JsonConvert.SerializeObject(new ResponseResult() { code=401,success = false,
            msg = "权限验证失败!"
        });
            //自定义返回的数据类型
            context.Response.ContentType = "application/json";
            //自定义返回状态码,默认为401 我这里改成 200
            context.Response.StatusCode = StatusCodes.Status200OK;
            //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            //输出Json数据结果
            context.Response.WriteAsync(payload);
            return Task.FromResult(0);
        }
    };



});

3、appsttings.json

  "ApiUser": {
    "UserName": "admin",
    "UserPassword": "123456"
  },
  "JWT": {
    "SecretKey": "assdfghkldsf@123!",
    "Issuer": "2222",
    "Expires": 10,
    "Audience": "22333"
  },

4、controllers


        /// <summary>
        /// 登录获取token
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userPasword">密码</param>
        /// <returns></returns>
        [FieldFilter]
        [HttpGet]
        public Models.ResponseModel.ResponseResult Login(string userName, string userPassword)
        {
            try
            {
                Models.ResponseModel.ResponseResult result = new Models.ResponseModel.ResponseResult();
                if (userName == _configuration["ApiUser:UserName"] && userPassword == _configuration["ApiUser:UserPassword"])
                {

                    // 1. 定义需要使用到的Claims
                    var claims = new[]
                    {
                new Claim("Id", "9527"),
                new Claim("Name", "Admin")
            };

                    // 2. 从 appsettings.json 中读取SecretKey
                    var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));

                    // 3. 选择加密算法
                    var algorithm = SecurityAlgorithms.HmacSha256;

                    // 4. 生成Credentials
                    var signingCredentials = new SigningCredentials(secretKey, algorithm);

                    // 5. 从 appsettings.json 中读取Expires
                    var expires = Convert.ToDouble(_configuration["JWT:Expires"]);

                    // 6. 根据以上,生成token
                    var token = new JwtSecurityToken(
                        _configuration["JWT:Issuer"],     //Issuer
                        _configuration["JWT:Audience"],   //Audience
                        claims,                          //Claims,
                        DateTime.Now,                    //notBefore
                        DateTime.Now.AddMinutes(expires),   //expires
                        signingCredentials               //Credentials
                    );

                    // 7. 将token变为string
                    var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

                    result.data = jwtToken;
                    result.success = true;
                    result.msg = "认证成功!";
                }
                else
                {
                    result.success = false;
                    result.msg = "用户名或密码错误!";
                }
                return result;
            }
            catch (Exception e)
            {
                string error = JsonConvert.SerializeObject(e);
                NetLog.WriteTextLog(error);
                throw;
            }

        }

5、使用

       [Authorize]
       [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
           string test_1= _configuration["Test2:test2_1"];

            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
;