[ASP.NET Core]使用JWT(Json Web Token)進行驗證授權

  • 3871
  • 0
  • 2018-01-15

在ASP.NET Core 2.0改變許多模組的整合與使用方式,也影響使用JWT進行驗證授權的相關設定,此篇將逐一記錄

  1. 在Configure中新增驗證模組並設定使用JWT驗證

    // Starpup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });
        services.AddAuthentication(x =>
            {
                x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //ValidateAudience = false,
                    ValidAudience = Configuration["JWT:Audience"],
                    //AudienceValidator = CustomAudienceValidator,
    
                    //ValidateIssuer = false,
                    ValidIssuer = Configuration["JWT:Issuer"],
                    //IssuerValidator = CustomIssuerValidator,
    
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["JWT:SignKey"]))
                };
                ////允許來自Query String的token
                //options.Events = new JwtBearerEvents()
                //{
                //    OnMessageReceived = ctx =>
                //    {
                //        // replace "token" with whatever your param name is
                //        if (ctx.Request.Method.Equals("GET") && ctx.Request.Query.ContainsKey("token"))
                //            ctx.Token = ctx.Request.Query["token"];
                //        return Task.CompletedTask;
                //    }
                //};
            });
    }
    
  2. 啟用驗證 & 套用驗證filter(本範例設定全域套用)

    // Starpup.cs > Configure
    app.UseAuthentication();
    // Starpup.cs > ConfigureServices
    services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });

     

  3. 處理登入 & JWT 簽章

    [Route("Login")]
    [AllowAnonymous]
    [HttpPost]
    public IActionResult Login([FromBody]TokenRequest request)
    {
        if (request.Username == "Jon" && request.Password == "123")
        {
            var claims = new[]
            {
    			//自訂payload附帶其他Identity其他屬性的type & value map宣告
                new Claim(ClaimTypes.Name, request.Username),
                new Claim(ClaimTypes.Role, "AdminRole")
            };
    
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JWT:SignKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
            var token = new JwtSecurityToken(
                issuer: _config["JWT:Issuer"],
                audience: _config["JWT:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);
    
            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
    
        return BadRequest("Could not verify username and password");
    }

     

  4. 測試

    >取回Token

    >存取資源

 以上就是在ASP.NET Core中如何啟用JWT驗證。