Search code examples
authenticationoauthmicroservicesvert.x

Better way to implement authentication in microservice architecture using vert.x


Someone have idea how to implement authentication and autorization process in vert.x microservice architecture thru API Gateway service and standalone user service, where it has own custom Auth provider? Should it use shared data (hazelcast map) to store some user information like name, roles by token or something else? I,m breaking mind..


Solution

  • Having a user service, I wanted all authentication and authorization operations to be performed through it. In the end, I did this:

    jdbcAuth.rxAuthenticate(authInfo)
                .map(user -> user.principal().getString("username"))
                .flatMap(username -> roleRepository.findByUsername(username).map(roles -> {
                    JWTOptions jwtOptions = new JWTOptions().setAlgorithm("RS256");
                    roles.forEach(jwtOptions::addPermission);
                    LOGGER.info("Token successfully created");
                    String token = jwtAuth.generateToken(new JsonObject().put("username", username), jwtOptions);
                    return new JsonObject().put("accessToken", token).put("tokenType", "Bearer");
                }))
                .subscribe(SingleHelper.toObserver(handler));
    
    1. For user authentication I use JDBCAuth (and solt hash generation for new user creation)
    2. If there is such user we are getting roles, generate a token with optional claims like "username" and JWTOptions with perrmissions.
    3. Putting into request header Authorization: Bearer --token--
    4. On other microservices we put global JWTAuth handler with pulicKey like:

      JWTAuthHandler.create(JWTAuth.create(vertx.getDelegate(), new JWTAuthOptions().addPubSecKey(new PubSecKeyOptions()
              .setAlgorithm("RS256")
              .setPublicKey(<PUBLIC_KEY>))));
      
    5. This handler sets the user to the context, and we can get it through context.user () and check the permissions. By the way, we can put this handler along with the addAuthority() method on the route for access checking.