JSON Web Token (JWT)

"JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties."

In the past, the stateless nature of HTTP was circumvented in a web application (most of them are stateful in nature) by associating each request with a session ID created on the server and then stored by the client using cookies. Each request sends the cookie (session ID) in the form of an HTTP header, which gets validated by the server, and a state (a user session) is associated with each request. In modern applications (we will cover this in a bit more detail in the next section), a server-side session ID is replaced with the JWT. The following diagram shows the workings of the JWT:

Figure 1: Workings of the JWT in modern applications

The web server, in this case, doesn't create a user session and the user session management capability needed for a stateful application is offloaded to other mechanisms.

In the world of the Spring Framework, the Spring Session module can be employed to externalize the session from the web server to a central persistence store (Redis, Couchbase, and so on). Every request containing a valid token (JWT) is validated against this external store of authenticity and validity. After successful authentication, applications can generate a valid token and send it as a response to the client. The client can then store this token in any client storage mechanism it uses (sessionStorage, localStorage, cookies, and so on, in a browser). Using Spring Security, we can validate this token to ascertain the authenticity and validity of the user and then do whatever is required. We have a dedicated example in a subsequent section (Simple REST API security) of this chapter, which uses a basic authentication mechanism and, if successful, creates the JWT. Subsequent requests use the token in the HTTP header, which gets validated on the server to give access to other secured resources.

The following points highlight some of the advantages of using the JWT:

  • Better performance: Each request, when reaching the server, has to check the authenticity of the token send. The authenticity of the JWT can be checked locally and doesn't require an external call (say, to a database). This local validation is performant and reduces the overall response time for a request.
  • Simplicity: JWT is easy and simple to implement. Also, it is a well established format in the industry for tokens. There are a number of well-known libraries which can be used to easily work with the JWT.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.150.75