JWT Authentication
Recently implemented JWT authentication in one of project, a JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret or a public/private key pair using RSA or ECDSA.
When it should use:
1) Authorization: Most commonly used for authorization.Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
2.) Information Exchange: As JWT is signed token it is a good way to transmit information between two parties.
JSON WebTokenStructure:
It consists of :
1) Header:The header mainly consists of two parts: the type of token, which is JWT, and the hashing algorithm that is used, such as HMAC SHA256 or RSA.
{
"alg": "HS256",
"typ": "JWT"
}
Then, this JSON is Base64Url-encoded to form the first part of the JWT.
2) Payload: It contains the claims. Claims are statements about an entity.
Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims.
Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined
Private claims: These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.
{
"sub": "1234567890",
"name": "Ravi Mishra",
"admin": true
}
3.) Signature: For creating signature , you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret)
Putting all together:
The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML.
The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlJBVkkgbUlTSFJBIiwiaWF0IjoxNTE2MjM5MDIyfQ.4q2wT2ZgqkexX3olulYE7ZUPzAVnX6isUzwynz6fvrQ