title: JWT Token for distrubuted system running on multiple server instance
body: <p>I am using <strong>JWT token</strong> for rest api's security. </p>
  
  <p>When user is logged in check user's credentials with DB.</p>
  
  <p>If it matched we are encrypting it for further security and then passing it to jwt to create a token</p>
  
  <p>Now in order to match user's token we need to keep password somewhere so that we can match them when user sends any request after logged in </p>
  
  <p>we can do it 2 ways 
  1. Keep detail in Database and each time rest call is fired check token with token in Database which is too costly for each rest call
  2. Preserve secret somewhere in JVM and use it. Here I have tried HttpSession from package </p>
  
  <p>javax.servlet.http.HttpServletRequest</p>
  
  <p><em>// My key issue code</em></p>
  
  <pre><code>// Encrypt it
      Key key = keyGenerator.generateKey(password);
      jwtToken = Jwts.builder()
              .setSubject(username)
              .setIssuer(uriInfo.getAbsolutePath().toString())
              .setIssuedAt(new Date())
              .setExpiration(toDate(LocalDateTime.now().plusMinutes(1)))
              .signWith(SignatureAlgorithm.HS512, key)
              .compact();
  </code></pre>
  
  <p>// Adding details to session</p>
  
  <pre><code>HttpSession httpSession = currentRequest.getSession();
  httpSession.setAttribute("userSecret", password)
  </code></pre>
  
  <p>This works fine for single Server instance.</p>
  
  <p>But at some point we need to scale up and run multiple instance of server. </p>
  
  <p><strong>How do we handle this case where user may logged in using 1 instance and may serving rest call using another instance using load balancing.</strong></p>
  
  <p><strong>As users secret is available only in first Server's JVM.</strong> </p>