# Json Web Token (JWT)
* JWT is used for both authentication and authorization in client-server system.
* Follows open standard (RFC 7519)
* JWT is the trusted way of authentication because it is digitally signed and secret using HMAC Algorithm or sometimes using a public/private key using RSA.
* Basically, HMAC stands for Hashed-based Message Authentication Code, it uses some great cryptographic hashing technique that provides us great security.
* Also, the JWT is part of great Authentication and Authorization Framework like OAuth and OpenID which will provide a great mechanism to transfer data securely.
## Structure
```
When a client authenticted by the server, server creats and sign the JWT token and send it to client.
```
1. Header
```json
{
"alg": "HS256",
"typ": "JWT"
}
```
2. Payload
```json
{
"sub": "1234567890",
"name": "Jaydeep Patil",
"admin": "true"
}
```
3. Signature
```go
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
//This is the Secret Key which is store at server side and use in signature
your-256-bit-secret
)
```

## How JWT's are signed
- Signature in JWT plays an important role in keeping the JWT safe from tampering.
- Signature gets created by Signing the JWT which involves the following steps:
- The header and payload of the JWT are encoded into base64.
- - The encoded header, the encoded payload, and a secret key are combined and signed using the specified signing algorithm. This creates a digital signature for the JWT.
For eg: JWT Signature for HMAC algo, can be obtained as below:

- The obtained signature is further encoded into base64.
- The encoded header, the encoded payload, and the encoded signature are combined to form the final JWT string.
- This JWT is then sent to the client.
For eg: Sample JWT looks like as below:

### How JWTs are verified?
- Whatever JWT received by client, is sent back again to Backend
- Backend splits the JWT into three parts: a) the encoded header, b) the encoded payload, c) and the encoded signature
- The encoded header and payload are decoded using base64 decoding
- The signature is also decoded and verified using the same secret key and signing algorithm that were used to sign the JWT.
- If the payload is tampered then signature won't match and JWT will be rejected by backend, otherwise it will be accepted.