Using JWT in a Microservice Architecture
This article shows how to use JWT for cross-service authentication/authorization.
Join the DZone community and get the full member experience.
Join For FreeIn a monolithic architecture, all the subsystems are in one application: authentication and authorization, session manager, business logic, etc. If we are talking about microservice architecture, some things get more complicated.
Microservices
In a microservice architecture, as a rule, authentication/authorization is a separate service.
To request a service, you must first authenticate and get an access token. An example is OAuth 2.0 Client Credentials Flow. To get a token, you need to pass the client id
and client secret
. In the example below, credentials are passed as an Authorization Basic header:
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
In response to this request, we will get an access token, which can be used to request the desired service. But how do we validate this token on the service side?
Validation
The most obvious way is to query the authorization service and introspect the token. But when our system contains hundreds of services, such requests can put a lot of load on the authorization service, and it can become a bottleneck at some point. To avoid this, we can verify the token in the service it was intended for. To do that, we can use self-contained tokens, which include JWT (JSON Web Tokens).
A JWT is a certain kind of token, which generally consists of three parts: a header, a body, and a signature. The standard is described in more detail in RFC7519.
Here the header specifies:
typ
– a type of token (we are considering JWT)alg
– signing algorithm (e.g. HS256 – HMAC with SHA-256(header + payload + secret))kid
– used when there is more than one key, and you need to understand which key is a signed token
The body consists of standard and custom tokens:
iss
– issuer (who issued token)aud
– audience (who the token is for)iat
– issued atexp
– expiration timesub
– subjectjti
– unique ID of JWT
Both symmetric (e.g., HS256) and asymmetric (e.g., RS256) signature algorithms can be used as a signature. In a symmetric algorithm, there is only one private key, which is used for both the signature and the verification. In an asymmetric algorithm, the signer uses a private key that only he keeps, and the verification of the signature can be done with a public key which can be distributed to everyone.
It turns out that such a signed token is self-sufficient and cannot be manipulated unnoticed by the receiving party. After receiving the token, the receiving party can verify the signature and make sure that the token has not been modified. This means all the data inside the token can be trusted. This eliminates the need to introspect the token by calling a remote service, thereby reducing the load on the service.
If service B receives a request that contains an access token, it needs a key to verify the signature. If we have a complex system with dozens of hundreds of microservices, the necessary services need to distribute this key. And if you use a symmetric algorithm, there is a high probability that the key can leak. And owning a private key, you can sign tokens of any content. Therefore, it is highly recommended to use an asymmetric algorithm. In this case, as a rule, an endpoint is placed on the authentication/authorization service, which returns a list of public keys for checking the signature. The necessary services need to query and cache these keys by themselves. With this approach, it is easy to organize the key rotation - at a certain moment, the auth-service can generate a new set of keys and start using it. After receiving such a new token, the receiving service, failing to find a cached key on its own, will request the auth-service again and receive an updated list of keys.
Example:
curl https://www.googleapis.com/oauth2/v3/certs
{
"keys": [
{
"alg": "RS256",
"kty": "RSA",
"use": "sig",
"n": "4DauU23AEpgBg3zJbqT8Fn-Zf817ru1moUjG75yJ-T0NpuQiggrXPn2YoKgo_qtnYloZh-RLjFfRv_Jb47riZhV5vsW7PiMR4MjlXgMWQlWG7kD9cIH5cTzBuEAzCkZZDu7XFkTfWUtRdWS5iKBjfQ465Qi5yFqfh7iHbQoKiN32pkWDI4MG8CUQC-YDbz77IRMpD39ZzNxkxYqbeJ226MrgKVGHFbmZLZPX8VX4r45NZifkPHa5-G5YDxaL622fkTqgPkyJtFOMy08X6K4BtVV0ZUJqi19bzEW970aI13seu0BzBsIspZ2NSPtljQqQFJTcW1EAmOCB5iNDi3J0mQ",
"e": "AQAB",
"kid": "fda1066453dc9dc3dd933a41ea57da3ef242b0f7"
},
{
"e": "AQAB",
"alg": "RS256",
"n": "yJdNun_DT8_krjOUFMk4UPb7KgOyoN2EIHVL77LFLUlzFwOLon1pEceYcWffNQnjdtzDCN5-q6DxlIiJyDgQhPPMpJzMcpZceo0tKd-Ve1RLEUVcbnbjyZ-inrxVWfYTOuWTsutt7EylFDIMfw1Dh14IccFG5loyLdtZX2yejhXmJzMCxTISE_lCxCIiIqu5filfc3AnnyNb66Mv_oyK5z22pc9f-dFAmT3e5IXA-0UkrEVtLl7lRGmWdBkAkEWzhh17aQ0BynxpcTX5efGyr2b5ktUObCNdKMwNE4_Berz4l7_Oz6-gWDlyjbROrHKx0B27SFHdtNHbYARJsfVsjw",
"kty": "RSA",
"kid": "1727b6b49402b9cf95be4e8fd38aa7e7c11644b1",
"use": "sig"
}
]
}
Having verified the token signature, we must check the iss
and aud
claims. The iss
must contain the identifier or URL of the authentication service. The aud
contains the identifier or list of identifiers of the services for which the token was generated. We must make sure that our system is present in this list and that this token is intended for us.
After all the checks, we can authorize the request and execute the necessary actions.
Token Revocation
It is important to note that one of the problems with self-contained tokens is the inability to simply revoke them. For example, a token is compromised, and we need to prohibit its use on all services in our system. But our services only do signature verification – the token continues to be valid.
In such cases, we keep the lifetime of the token short (minutes), after which it will no longer be valid. But if that's not enough and the token needs to be revoked instantly, you can use a token blacklist as a key-value repository, which will store the IDs of the revoked tokens (jti
). Then each service should query that storage and make sure that the token is not on the list. It is not necessary to store tokens in this repository permanently, but only for the time until we reach the exp value in the token. In addition, the token revocation event itself is quite rare, so the storage will be small and read-loaded.
Sensitive Information
It should be understood that the content of the token is not encrypted and that the body of the token can be read. If you have to give the token to third-party services, then you should be careful with the data you put in the body of the token. But if that data is needed, you can use an encrypted version of the token (JWE). Another approach is not to give out the full token but only its identifier (jti
), storing the jti
– full token mapping in the repository/cache. And at the next request, exchange jti
to the full token and work with the full token inside your system.
Conclusion
Proper use of JWT in cross-service authentication/authorization implementations allows us to build flexible, secure, high-load applications. And understanding how it works will reduce the likelihood of introducing vulnerabilities when building a system architecture.
Opinions expressed by DZone contributors are their own.
Comments