1. AspNetCore 實現JWT(使用Microsoft.AspNetCore.Authentication.JwtBearer)

概述

在AspNetCore 中實現Jwt比較簡單,使用Microsoft.AspNetCore.Authentication.JwtBearer 庫,再加幾行代碼即可.

步驟(2.x/3.x通用)

1.新建一個AspNetCore WebApi項目.
2.創建獲取token的方法

    public static class JwtHelper
    {
        public  static string GeneratorToken(string username)
        {
            // 服務端密鑰 一般16bit 以上
            var secret = "1234567890123456";

            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            // 加密算法
            var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
            // 自定義claims
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name,username)
            };
            var token = new JwtSecurityToken(
                "issuer", // 發行者
                "audience", // 使用者
                claims,
                expires: DateTime.Now.AddMinutes(60),
                signingCredentials: credentials
                );
            return new JwtSecurityTokenHandler().WriteToken(token);
            
        }         
    }
  1. 新建一個token控制器
    public class TokenRequest
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }


    [ApiController]
    [Route("[controller]")]
    public class TokenController:ControllerBase
    {
        [HttpPost("")]
        public async Task<IActionResult> GetToken([FromBody]TokenRequest request)
        {
            // 驗證用戶名密碼
            var token = JwtHelper.GeneratorToken(request.UserName);
            return Ok(token);
        }
    }
  1. Startup 註冊和啓用中間件
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthentication(
                JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Events = new JwtBearerEvents()
                    {
                        OnMessageReceived = context =>
                        {
                            context.Token = context.Request.Cookies["access_token"];
                            return Task.CompletedTask;
                        }
                    };
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "issuer",
                        ValidAudience = "audience",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567890123456"))
                    };

                });
        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

  1. 驗證獲取token

6.驗證api(使用Authorize過濾器)

  • 沒有token時

  • 帶上token時

說明

使用 驗證如下

1. 加密後的jwt token 包含三個部分,分別是包含源數據說明的HEADER、包含自定義聲明信息的PAYLOAD、以及用於驗證的簽名簽名信息 SIGNATURE

2. 在分佈式生產環境中,api 和token server 分別維護各自的公鑰.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章