Search code examples
jwtbearer-tokenwebsecurity

When to validate JWT


I am building an application that spans over several parts of infrastructure.

An end-user can sign in to a portal using OAuth 2.0 authorization code flow. When calling different APIs, the portal requests tokens on-behalf-of the signed in user and attaches those to outgoing requests. The tokens received to call external APIs have an aud claim matching the target API.

When a call to an external API is fired, it first passes through an API Gateway. This API Gateway validates the token and ensures the aud claim is actually intended for this endpoint. It also verifies roles and a few other claims.

When the gateway checks pass, the request is forwarded to the actual implementation. Now the actual implementation also verifies the token, but only that the token is valid (e.g. not looking at specific claims). That is not to say that the claims aren't used internally in the application after the token is validated, roles are very much part of the application logic.

So to summarize this as bullet points:

  1. User signs in to portal
  2. User performs some action that causes an API call
  3. Portal attaches token to outgoing request
  4. Request hits gateway for 1..n claims are validated
  5. Request is forwarded to actual implementation
  6. Implementation again validates token is valid, not looking at claims

All endpoints are public, e.g. I could call any of these from anywhere as long as I have a token.

In the above outlined scenario, I'm handling the token properly?

In general, what is the recommendation for tokens passing through several layers of an application? Should every layer validate the token? If yes, are there exceptions to the rule?


Solution

  • Typically, JWT tokens are validated when are sent from the client-side to the server-side. As these tokens are signed, if anyone tries to tamper with the token before sending it to the server-side endpoint, the token verification will fail, therefore these tokens are a secure way of sending the session of an authenticated user to an API or a server endpoint.

    These JWTs can be also transferred between servers or different application layers, and it always would be a good practice to verify the token before processing it. It is adding a layer of security to avoid anyone sending tokens to that layer directly and skipping the validation.