6

I am using JWT token for rest api's security.

When user is logged in check user's credentials with DB.

If it matched we are encrypting it for further security and then passing it to jwt to create a token

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

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

javax.servlet.http.HttpServletRequest

// My key issue 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();

// Adding details to session

HttpSession httpSession = currentRequest.getSession();
httpSession.setAttribute("userSecret", password)

This works fine for single Server instance.

But at some point we need to scale up and run multiple instance of server.

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.

As users secret is available only in first Server's JVM.

1 Answer 1

12

You can share the private key, which was used for encrypting the JWT, among the servers. When a servers gets an API call, you can try to decrypt the JWT with the private key. If the decryption is successful, you have a valid a JWT and you can process the request. If the decryption fails, that means it's an invalid JWT. Once a JWT has been created, you don't need to hit the database. That's the primary usage of JWT in my opinion. I am not sure what you mean by userSecret.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.