vs2022 搭建NET6 WebApi 接口项目《四》 配置Jwt获取登录令牌

1、添加验证

     

#region 添加验证校验
builder.Services.AddAuthentication(o =>
{
    o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    o.DefaultChallengeScheme = nameof(ApiResponseHandler);
    o.DefaultForbidScheme = nameof(ApiResponseHandler);
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidAudience = "TestApiAdmin",
        ValidIssuer = "TestApiAdmin",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppsettingHelper.Get("JwtSecurityKey"))),
    };
}).AddScheme<AuthenticationSchemeOptions, ApiResponseHandler>(nameof(ApiResponseHandler), o => { });

2、启用验证

    

app.UseAuthentication();
app.UseAuthorization();

3、ApiResponseHandler类代码

    

  public class ApiResponseHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public ApiResponseHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            throw new NotImplementedException();
        }
        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status401Unauthorized;
            await Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE401)).MessageModel));
        }

        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status403Forbidden;
            await Response.WriteAsync(JsonConvert.SerializeObject((new ApiResponse(StatusCode.CODE403)).MessageModel));
        }

    }
 public class ApiResponse
    {
        public int Status { get; set; } = 200;
        public string Value { get; set; } = "";
        public string MessageModel { get; set; } = "";
        //public MessageModel<string> MessageModel = new MessageModel<string>() { };

        public ApiResponse(StatusCode apiCode, string msg = null)
        {
            switch (apiCode)
            {
                case StatusCode.CODE401:
                    {
                        Status = 401;
                        Value = "很抱歉,您无权访问该接口,请确保已经登录!";
                    }
                    break;
                case StatusCode.CODE403:
                    {
                        Status = 403;
                        Value = "很抱歉,您的访问权限等级不够,联系管理员!";
                    }
                    break;
                case StatusCode.CODE404:
                    {
                        Status = 404;
                        Value = "资源不存在!";
                    }
                    break;
                case StatusCode.CODE500:
                    {
                        Status = 500;
                        Value = msg;
                    }
                    break;
            }

            //MessageModel = new MessageModel<string>()
            //{
            //    status = Status,
            //    msg = Value,
            //    success = apiCode != StatusCode.CODE200
            //};
        }
    }

    public enum StatusCode
    {
        CODE200,
        CODE401,
        CODE403,
        CODE404,
        CODE500
    }

 4、在appsetting.json设置密钥

      

 "JwtSecurityKey": "fdsfdsfdsgs65rdt354qwrre34",

5、登录控制器获取令牌

      

 [ApiController]
    [Route("api/[controller]/[action]")]
    public class AuthController : BaseController
    {
        readonly IConfiguration _config;
        public AuthController(IConfiguration config)
        {
            _config = config;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("login")]
        public async Task<IActionResult> LoginAsync(LoginDto model)
        {
            var view = new LoginView
            {
                Expires = DateTime.Now.AddDays(30)
            };
            var claims = new[] { new Claim(ClaimTypes.NameIdentifier, model.LoginName) };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSecurityKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: "TestApiAdmin",
                audience: "TestApiAdmin",
                claims: claims,
                expires: view.Expires,
                signingCredentials: creds);
            view.Token = new JwtSecurityTokenHandler().WriteToken(token);
            return Ok(view);
        }
    }

 6、新建一个BaseController api控制器作为基类,以便在获取令牌之后,可以直接操作登录用户信息

    

 [ApiController]
    public class BaseController : ControllerBase
    {
        protected virtual string? CurrentUserId => HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    }

 7、获取令牌操作结果

      

 

      

 

posted @ 2022-04-08 23:44  程序原快递  阅读(1297)  评论(0编辑  收藏  举报