The JWT is the result of the authentication. For example
- User sends his credentials (e.g. username/password) to an authentication service. It could be a third party one or one inside your monolith or your own microservices dedicated to authentication.
- The service validates username-password. If authentication success it returns an JWT that represents that the user is already authenticated, in other words he is who claim he is. This JWT could contain a payload without sensitive information (don't store the password here).
- The user sends another request to a service business with the JWT. If the JWT isn't expired and is not corrupted (the sign is still valid) then the service could trust in its JWT. Maybe this task will be delegated to an authorization service.
What is inside the JWT token?
Well, the simplest JWT contains information about the sign (I can't enter in much detail here because I'm not a security expert) that allows to check if the sign has been corrupted when a request with the JWT is received.
This information can be verified and trusted because it is digitally signed
Besides that, the JWT allows to send a payload.
More formally, the JWT is composed by:
- Header: type of the token + hashing algorithm being used
- Payload: Claims are statements about an entity (typically, the user) and additional metadata.
- Signature: The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.
For example, if I send a request to a authentication service with my credentials username:password being gabriel:giussi, it will check these credentials and if they're OK it could create the following JWT:
Then with every request I will then the encoded JWT that contains my username and the service will
- Perform authorization (What Gabriel is authorized to do?) if the JWT sign is valid.
- Ask me to login again if the JWT has expired
- Return an authentication error if the sign is broken.