Learning JWT Part 1
===

---
###### tags: `JWT`
The following content most came from [JWT Introduction](https://jwt.io/introduction).
## What is JWT
**JWT** refers to **JSON Web Token**, it is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON objetc.
JWT can be using:
1. A secret key with th **HMAC** algorithm.
2. Public / private key pair with RSA or ECDSA algorithm.
> References
> 1. [Wiki: HMAC](https://zh.wikipedia.org/zh-tw/HMAC)
> 2. [訊息鑑別碼 - Message authentication code](https://ithelp.ithome.com.tw/articles/10244249)
> 3. [RSA加密演算法](https://zh.wikipedia.org/zh-tw/RSA%E5%8A%A0%E5%AF%86%E6%BC%94%E7%AE%97%E6%B3%95)
> 4. [橢圓曲線數位簽章算法 Elliptic Curve Digital Signature Algorithm (ECDSA)](https://iris123321.blogspot.com/2021/07/bmcpfr-elliptic-curve-digital-signature.html)
## When should use JWT?
We can use JWT in some scenarios like:
1. **Authorization**
- [JWT Authentication Use case and Workflow](https://documentation.softwareag.com/webmethods/compendiums/v10-5/C_API_Management/index.html#page/api-mgmt-comp/co-jwt_usecase_workflow.html)

2. **Information Exchange**
Using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
## What's the JWT Structure?
- **Header**, consists of two parts:
- the type of the token.
- the signing algorithm being used.
```
{
"alg": "HS256",
"typ": "JWT"
}
```
- This JSON is **Base64Url** encoded to form the first part of the JWT.
- **Payload**, contains the **claims**, claims are statements about an entity and additional data. There are three types of claims:
- **Registered claims**
- **Public claims**
- **Private claims**
```
{
"sub": "1234567",
"name": "John",
"admin": true
}
```
- **Signature**, have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.The signature is used **to verify the message wasn't changed along the way**, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.
```
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
```
## How do JSON Web Tokens works?
1. User successfully logs in using their credentials.
2. JSON Web Token will be returned.
3. Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the **Authorization** header using the **Bearer** schema.
> Be aware of stroing sensitive session data in browser storage due to lack of security.
> Reference: [Storage APIs](https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html#local-storage)