Search code examples
javajwtrsapublic-key-encryptionvert.x

Handshake in JWT public/private key authentication using vertx


I created a small vertx auth-server which signs/generates JWT tokens using public/private key.

        PrivateKey privateKey = CertUtil.getPrivateKey("config/private_key.der");
        PublicKey publicKey = CertUtil.getPublicKey("config/public_key.der");

        // Create a JWT Auth Provider
        JWTAuth jwt = JWTAuth.create(vertx, new JWTAuthOptions()
                .setPubSecKeys(List.of(new PubSecKeyOptions()
                        .setAlgorithm("RS256")
                        .setPublicKey(Base64.getEncoder().encodeToString(publicKey.getEncoded()))
                        .setSecretKey(Base64.getEncoder().encodeToString(privateKey.getEncoded())))));
        // protect the API
        router.route("/api/*").handler(JWTAuthHandler.create(jwt, "/api/new-token"));

        // this route is excluded from the auth handler
        router.get("/api/new-token").handler(ctx -> this.generateAndSendToken(ctx, jwt));

        // this is the secret API
        router.get("/api/protected").handler(ctx -> {
            ctx.response().putHeader("Content-Type", "text/plain");
            ctx.response().end("a secret you should keep for yourself...");
        });

        vertx.createHttpServer().requestHandler(router).listen(8080);

now when i access /api/new-token from client i get a JWT token back signed from my auth-server above. however I have some open questions:

  • How is auth-server making sure that client has server public key and it is genuine?
  • How can client send public key to auth-server?
  • How can i make /api/new-token secure so only legitimate client can connect to it?

Solution

  • Why don't you delegate this task to KeyCloak an Open Source Identity and Access Management. It adds authentication to your app and secures services with minimum fuss.

    We have used it into our project and it works pretty well!

    To plug it with Vert.x, you can follow these tutos :