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、獲取令牌操作結果

      

 

      

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM