【问题标题】:JWT token validation in ASP.NETASP.NET 中的 JWT 令牌验证
【发布时间】:2018-08-30 15:45:28
【问题描述】:

我正在 ASP.NET 中编写一个 API,它公开两个端点:一个用于生成 JWT 令牌,另一个用于验证给定令牌。

令牌生成似乎工作正常:

 [HttpPost]
        public IHttpActionResult Token()
        {
            var headerAuth = HttpContext.Current.Request.Headers["Authorization"];
            if (headerAuth.ToString().StartsWith("Basic"))
            {
                var credValue = headerAuth.ToString().Substring("Basic".Length).Trim();
                var usernameAndPassEnc = Encoding.UTF8.GetString(Convert.FromBase64String(credValue));
                var usernameAndPass = usernameAndPassEnc.Split(':');

                LdapAuthentication ldap = new LdapAuthentication();

                if (ldap.IsAuthenticated(usernameAndPass[0], usernameAndPass[1]))
                {
                    var claimsData = new[] { new Claim(ClaimTypes.Name, usernameAndPass[0]) };
                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret"));
                    var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                    var tokenString = new JwtSecurityToken(
                        issuer: "http://my.website.com",
                        audience: "http://my.tokenissuer.com",
                        expires: DateTime.Now.AddMinutes(1),
                        claims: claimsData,
                        signingCredentials: signInCred
                        );

                    var token = new JwtSecurityTokenHandler().WriteToken(tokenString);
                    return Ok(token);
                }
            }

            return BadRequest("Bad request");
        }  

但我不知道如何验证给定的令牌,在 ASP.NET Core 中我以这种方式实现它(效果很好):

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = "http://my.website.com",
                    ValidAudience = "http://my.tokenissuer.com",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret"))
                };
            });
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();
            app.UseMvc();
        }

那么,如何在 ASP.NET 中验证 JWT 令牌?

【问题讨论】:

  • 验证 JWT 令牌是什么意思?
  • 我的意思是检查没有人修改过令牌。在 JWT 网页调试器jwt.io中验证签名
  • 您通常没有单独的端点,而是用[Authorize] 装饰您的API 并让中间件为您完成工作。我建议阅读 Taiseer Joudeh's blog 作为如何在 ASP.NET 中进行此操作的一个很好的介绍
  • 您还有官方的 MS 文档:blogs.msdn.microsoft.com/webdev/2017/04/06/…
  • 是的,但我想在一个单独的服务中实现所有的身份验证逻辑,该服务将独立部署。各种应用程序将使用该身份验证。

标签: c# asp.net jwt


【解决方案1】:

为此,您可以编写一个中间件或使用现有的 Authorize 过滤器并覆盖它。使用以下方式验证令牌

    public static bool ValidateToken(string authToken) // Retrieve token from request header
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = this.GetValidationParameters();

        SecurityToken validatedToken;
        IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
        Thread.CurrentPrincipal = principal;
        HttpContext.Current.User = principal;
        return true;
    }

    private static TokenValidationParameters GetValidationParameters()
    {
        return new TokenValidationParameters
        {
            IssuerSigningToken = new System.ServiceModel.Security.Tokens.BinarySecretSecurityToken(symmetricKey), //Key used for token generation
            ValidIssuer = issuerName,
            ValidAudience = allowedAudience,
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateAudience = true
        };
    }

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2020-08-22
    • 2020-09-04
    • 2020-07-01
    • 2017-08-11
    • 2021-12-17
    • 2019-06-23
    • 2017-07-27
    • 2016-01-17
    相关资源
    最近更新 更多