JSON Web Token (JWT, pronounced jot) is a relatively new token format used in space-constrained environments such as HTTP Authorization headers. JWT is architected as a method for transferring security claims based between parties - wikipedia
JSON Web Tokens are an open standard (RFC 7519). There are a number of Benefits of JWT's which make them more compliant with modern REST principles - notably not storing state on the server (as the tokens contain the information required withim them).
The tokens are signed by the server's key, so the client and server are both able to verify that the token is legitimate. The tokens are designed to be compact , URL-safe and usable especially in web browser single sign-on (SSO) context.
- Need to be stored (local/session storage or cookies) - Tokens can expire like cookies - Local/session storage won't work across domains - Preflight requests will be sent on each CORS request - It's easier to deal with XSS than XSRF - Watch out for token size - If you store confidential info, encrypt the token - JSON Web Tokens can be used in OAuth
Tokens are not silver bullets, think about your authorization use cases carefully.
# Structure
JWTs generally have three parts: a header, a payload, and a signature. The header identifies which algorithm is used to generate the signature, and looks something like this:
header = '{"alg":"HS256","typ":"JWT"}'
HS256
indicates that this token is signed using HMAC-SHA256.
The payload contains the claims to make:
payload ='{"loggedInAs":"admin","iat":1422779638}'
As suggested in the JWT spec, a timestamp called <code>iat</code> (issued at (#Standard_fields)) is installed.
The signature is calculated by base64url encoding the header and payload and concatenating them with a period as a separator:
key = 'secretkey'
unsignedToken = encodeBase64Url(header) + '.' + encodeBase64Url(payload)
signature = HMAC-SHA256(key, unsignedToken)
To put it all together, the signature is base64url encoded. The three separate parts are concatenated using periods:
token = encodeBase64Url(header) + '.' + encodeBase64Url(payload) + '.' + encodeBase64Url(signature) # token is now: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dnZWRJbkFzIjoiYWRtaW4iLCJpYXQiOjE0MjI3Nzk2Mzh9.gzSraSYS8EXBxLN_oWnFSRgCzcmJmMjLiuyu5CSpyHI
The output is three Base64url strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact compared to XML-based standards such as SAML.
Typical cryptographic algorithms used are HMAC with SHA-256 (HS256) and RSA signature (Digital signature) with SHA-256 (RS256). JWA (JSON Web Algorithms) RFC 7518 introduces many more for both authentication and encryption.
# See also * Use * Standard fields * Implementations - Benefits of JWT's