3

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

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

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

8
  • What you mean by validate JWT Token ? Commented Mar 21, 2018 at 13:36
  • I mean check that no one has modified the token. Verify the signature like in the JWT webpage debugger jwt.io Commented Mar 21, 2018 at 13:42
  • 2
    you usually don't have a separate endpoint for that but decorate your API with [Authorize] and let the middleware do the work for you. I recommend reading Taiseer Joudeh's blog as a good introduction on how to do it in ASP.NET Commented Mar 21, 2018 at 13:46
  • You have also the official MS Documentation : blogs.msdn.microsoft.com/webdev/2017/04/06/… Commented Mar 21, 2018 at 13:47
  • 1
    Yeah, but I want to implement all of the authentication logic in a separate service which will be deployed independently. And various applications will use that authentication. Commented Mar 21, 2018 at 13:48

1 Answer 1

6

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
        };
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.