Search code examples
authenticationjwtvert.x

Authenticating JWT Vertx


I have successfully generated a JWT token using RSA Keys from the documentation, I want to secure the endpoints and authenticate JWT, that's where I got stuck. Here is what I have done

AuthConfig

        JWTAuthOptions options = new JWTAuthOptions()
                // add public key
                .addPubSecKey(new PubSecKeyOptions()
                        .setAlgorithm(algorithm)
                        .setBuffer("-----BEGIN PUBLIC KEY-----\n" +
                                publicKey String
                                "-----END PUBLIC KEY-----"))
                // add private key
                .addPubSecKey(new PubSecKeyOptions()
                        .setAlgorithm(algorithm)
                        .setBuffer("-----BEGIN PRIVATE KEY-----\n" +
                                privatekey String
                                "-----END PRIVATE KEY-----"));

        return JWTAuth.create(vertx, options);
    }

JWTBuilder

 public JwtBuilderHandlerImpl(JWTAuth jwtAuth) {
        this.jwtAuth = jwtAuth;
    }

public String buildToken(String subject) {
       return jwtAuth.generateToken(new JsonObject()
                       .put("message", "token-data"),
               new JWTOptions()
                       .setHeader(new JsonObject().put("Bearer", "Bearer"))
                       .setSubject(subject)
                       .setIssuer(issuer)
                       .setAlgorithm(algorithm)
                       .setExpiresInMinutes(2840));

    }

The build token method is called from the controller to generate the JWT token


Solution

  • You will need and endpoint that will exchange generate JWT (call your controller) so that the user can obtain it. Also you will need to protect all other resources so that they can be only accessed with valid JWT generated from your app.

    Here is simple example to protect all endpoints starting with /api/ so that they require valid JWT:

    router.route("/api/*").handler(JWTAuthHandler.create(jwt));
    

    Also for more detailed example please check official example: vertx-jwt-example