Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating ADAL JWT token in C# REST service

I have a web application which uses the ADAL library for authentication through Azure Active Directory.

This web application makes a call to a C# REST service by passing the ADAL token string as a parameter. In my REST service, I want to validate this token. If the token is valid only then the service will perform the operation.

I searched a lot but could not find a way to validate the JWT token in my rest service. Can you guys please help me on this?

like image 389
Yash Verma Avatar asked Feb 24 '16 15:02

Yash Verma


1 Answers

You have two options:

1. Use OWIN middleware

Use middleware that will handle token validation for you. A common case will be the OWIN middleware, which does all the magic for you. Usually, this is the best approach, as it allows you to focus your code on the business logic for your API, not on low-level token validation. For a sample REST API that uses OWIN, check out these two samples:

  • https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect
  • https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnet5

2. Manual JWT validation

You can use the JSON Web Token Handler for ASP.NET to do manual JWT token validation. (Ok, so it's not entirely manual, but it is manually invoked.) There's also a sample for this:

  • https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation (the actual JWT validation happens in Global.asax.cs and looks something like this:

    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    
    TokenValidationParameters validationParameters = new TokenValidationParameters
    {
        ValidAudience = audience,
        ValidIssuer = issuer,
        IssuerSigningTokens = signingTokens,
        CertificateValidator = X509CertificateValidator.None
    };
    
    try
    {
        // Validate token.
        SecurityToken validatedToken = new JwtSecurityToken();
        ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);
    
        // Do other validation things, like making claims available to controller...
    }
    catch (SecurityTokenValidationException)
    {
        // Token validation failed
        HttpResponseMessage response = BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
        return response;
    }
    
like image 144
Philippe Signoret Avatar answered Oct 22 '22 16:10

Philippe Signoret