Authentication
![Authentication](/assets/img/blog/example-content-iii.jpg)
A page showing Hydejack-specific markdown content.
Advantages and Disadvantages of usin token-based authentication.
- Token-based authentication
- Session-based authentication
- Advantages and Disadvantages of usin token-based authentication
- Json Web Token (JWT)
Token-based authentication
This is the difference between token and cookie! ref: https://cdn.auth0.com/blog/cookies-vs-tokens/cookie-token-auth.pngs
Users enter their log credentials (username + password).
Server varifies the credentials -> if correct -> creates an encrypted and signed token, with a private key.
On client side, stores the token returned from server.
On subsequent requests, the token is decoded with the same private key -> if valid, the request processed.
Once the user logout the app, the token is destroyed on client-side, no interaction with server is necessary.
Session-based authentication
Users enter their log credentials (username + password).
Server varifies the credentials -> if correct -> creates a session -> return sessionID to user -> store the session to database.
On client side, stores the sessionID returned from server.
On subsequent requests, the sessionID will be varified against the one stored in database -> if match, request processed.
Once the user logout the app, the session is destroyed on the server side.
Advantages and Disadvantages of usin token-based authentication
Stateless: backend no need to keep a record of tokens.
Self-contained: no need to loop up in Databse, server contains all data it required for checking the validity.
But the size of token is larger than sessionID.
Json Web Token (JWT)
JWT work flow. ref: https://dev.to/mattgahrns/what-is-a-jwt-fb5
JWT is a long string as shown in the image above. It contains three main parts: 1) the Header 2) the Payload and 3) the Signature Header.Payload.Signature.
Inside Header is a JSON object, describing the JWT’s Metadata. Header is converted to the string we see by using Base64URL algorithm.
Inside Payload is also a JSON object, storing the real data we would like to send. We could add different params like: “sub”, “name”, “admin” etc. This part will also be converted to string by Base64URL algorithm.
The third part is a signature to the prious two parts, to ensure the security of the information. Server will generate a secret (only server knows the secret, it won’t be sent to client), and then generate the Signature by using HMACSHA256 algorithm following this function
Then concat the three parts together by using ‘.’ to generate the token sent to users.