[CS] Token Day-84


Why use Token authentication?


Session authentication is cost by the server, while token authentication is cost by the client.

What is Token?


It is easy to think of tokens used as money.
  • Tokens used in the arcade
  • Tokens used to enter the Concert hall
  • Proof of permission to use the facility.
    Token authentication was invented as a way to pay for the client. If the client has the token, Client can use the service that matches the token's authority.

    Isn't it risky to store tokens on the client?


    Tokens can contain information encrypted, so they can be stored on the client.

    Representative token authentication


    JWT (Json Web Token)

    What is JWT?


    Json Web Token
    Web token that stores attributes about the user information in Json format.

    JWT type


  • Access Token
    Grants access to protected information. When a client first authenticates, client receives two types of access tokens and refresh tokens. It is the access Token that actually gets the permission. However, the access token cannot be used for a long time because the validity period is set short.

  • Refresh Token
    When the validity period of the access token expires, a new access token is issued used by refresh token. However, for security reasons, some companies don't make refresh tokens.
  • JWT Structure



    Header

  • type of the token
  • what signing algorithm being used
  • {
      "alg": "HS256",
      "typ": "JWT"
    }

    Payload

  • Data
  • Authentication Level
  • etc..
  • {
      "sub": "data",
      "name": "John Doe",
      "admin": true
    }

    Signature

  • encoded header and encoded payload result
  • HMACSHA256(
      base64UrlEncode(header) + "." +
      base64UrlEncode(payload),
      secret)
    ex) Result

    Token authentication process


  • The client sends a login request to the server with Id and Password.

  • Verifying Id and password match in the database after Server generates encrypted token.

  • Send the token to the client.

  • Client stores the token receives from the server. (localStorage, cookie, state, etc..)
  • 5-1. (The client can use the received token.)
    5-2. Put a token in the header and send Get request to the server.
  • The server decrypts the token, and if token is correct, responds to the client's request.
  • Advantages of token authentication


  • ステータスと拡張性なし
    There is no need for the server to bear the cost.

  • stability
    It is secure because encrypted.

  • Token generation is possible on a other server. no need to use main server.

  • Made Authorization easy
    Can authorize what information can be accessed by token
  • ex)
  • Grant permission to use photos and contacts
  • Only Pic
  • Only Contacts