ASP.NET中的JWT令牌验证 [英] JWT token validation in ASP.NET

查看:76
本文介绍了ASP.NET中的JWT令牌验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an API in ASP.NET that exposes two endpoints: one to generate a JWT token and other to validate a given token.

令牌生成似乎工作正常:

The token generation seems to work fine:

 [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中,我以这种方式实现了它(工作正常):

But I don't know how to validate a given token, in ASP.NET Core I implement it in this whay (which works fine):

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令牌?

So, how can I validate a JWT token in ASP.NET?

推荐答案

为此,您可以编写中间件,也可以使用现有的Authorize过滤器并将其覆盖.使用以下方法来验证令牌

For that either you can write a middleware or use the existing Authorize filter and override it. Use the following way to validate the token

    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
        };
    }

这篇关于ASP.NET中的JWT令牌验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆