Vertx JWTAuth instance caching

322 Views Asked by At

In Vert.x documentation here, I see that you can get an instance of a JWTAuth object and use it in a handler. I'm not sure whether I can store the reference to the object in a static or instance variable to use it later for creating new tokens for multiple requests. I was planning to create a class to manage JWT token authentication and get a reference to a JWTAuth object on the constructor. Then, on the method that gets called by the handler, use the reference stored in an instance variable to create the token. Is this ok? Or the API was designed to work best by calling JWTAuth.create() every time I need it?

For example,

Util class

public class AuthenticationUtil {
   private JWTAuth auth;

   public AuthenticationUtil(Vertx vertx) {
      JsonObject authConfig = new JsonObject().put("keyStore", new JsonObject()
          .put("type", "jceks")
          .put("path", "keystore.jceks")
          .put("password", "secret"));

      auth = JWTAuth.create(vertx, authConfig);
   }

   public void getToken(RoutingContext context) {
       if (validateCredentials(context.request().getParam("username"), context.request().getParam("password"))) {
           context.response().end(auth.generateToken(new JsonObject(), new JWTOptions()));
       } else {
           context.fail(401);
       }
   }

   public Handler<RoutingContext> createAuthHandler() {
       return JWTAuthHandler.create(auth);
   }
   ...
}

ServerVerticle

@Override
public void start(Future<Void> future) {
    AuthenticationUtil authUtil = new AuthenticationUtil(vertx);
    ...
    router.post("/auth").blockingHandler(authUtil::getToken);
    router.get("/someProtectedResource1").handler(authUtil.createAuthHandler());
    router.get("/someProtectedResource2").handler(authUtil.createAuthHandler());
    ...
}

What if I create many server verticles, and want to share the same AuthenticationUtil instance for all of them?

1

There are 1 best solutions below

0
On BEST ANSWER

It is safe to share a single JWTAuth instance. The implementation does not mutate any state after object initialization and the non thread safe Crypto calls are synchronized. However, if you can spend the little memory extra, you should create one instance per verticle in order to avoid synchronization.