Skip to content

Token Authentication With JWT#

Token In Authentication And Authorization#

  • A Token can be a plain string of format universally unique identifier (UUID) or it can be of type JSON Web Token (jwt) usually that get generated when the user is authenticated for the first time during login.
  • On every request to a restricted resource, the client sends the access token in the query string or the Authorization header. Then the server will validate the token and if the token is valid, the server will return the secure resource to the client.

sequenceDiagram

  Client->>Auth Server/App: /user/login with username and password
  Note right of Auth Server/App: Auth Server/App will generate the token <br/> and send to client. At the same time <br/> it stores the token and <br/> client details in the memory/DB.
  Auth Server/App->>Client: 7a200c16-38e8-4fe7-9964-196030bf4854 <br/> returns a token to the client
  Note left of Client: Client will receive the token <br/> after successful login in <br/> a header/query string etc.
  Note left of Client: Client system has to make sure <br/> to send the same token value <br/> on all the futher request to the <br/> backend server for protected resources
    Client->>Auth Server/App: /user/account <br/> 7a200c16-38e8-4fe7-9964-196030bf4854
    Note right of Auth Server/App: When a Client make a request with <br/> the token, the server will validate <br/> the token and return the protected <br/> resources if it is a valid.
    Auth Server/App->>Client: token is valid. return the account details

Advantages Of Token Based Authentication#

  • Token helps us not to share the credentials for every request which is a security risk to make credentials send over the network frequently.
  • Tokens can be invalidated during any suspicious activities without invalidating the user credentials.
  • Tokens can be created with a short life span.
  • Tokens can be used to store the user related information like roles/authorities etc.
  • Reusability: we can have many separate servers, running on multiple platfroms and domains, reusing the same token for authenticating the user.
  • Security - Since we are not using Cookie, we don't have to protect against CSRF - Cross-Site Request Forgery attacks.
  • Stateless, easier to scale. The token contains all the information to identify the user, eliminating the need for the Session state. If we use a load balancer, we can pass the user to any server, instead of being bound to the same server we logged in on.
  • We already used tokens in the previous sections in the form of CSRF and JESSIONID tokens.
    • CSRF Token protected our application from CSRF attacks.
    • JSESSIONID is the default token generated by the Spring Security which helped users not to share the credentials to the backend service every time.

Deep Dive In JWT#

See Also#

References#