Authentication


1. Token-based authentication

  • 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.

2. 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.

token

Image ref: https://cdn.auth0.com/blog/cookies-vs-tokens/cookie-token-auth.png

3. 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.

4. Json Web Token (JWT)

jwt

  • 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

    1
    2
    3
    4
    HMACSHA256(
    base64UrlEncode(header) + "." +
    base64UrlEncode(payload),
    secret)
  • Then concat the three parts together by using ‘.’ to generate the token sent to users.


Author: Luchen
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Luchen !
  TOC