如何在Vert.x REST服务中转发jwt令牌

时间:2018-03-01 16:20:19

标签: jwt vert.x

我有一个Vert.x REST服务,它接收带有jwt令牌的请求,我想调用另一个REST服务传递收到的令牌。在路由器处理程序和WebClient调用之间,我有一个业务逻辑层。我的问题是,是否有一种方法为webClient提供令牌,而不是通过我的业务逻辑层显式传递它?换句话说,有可能以某种方式检索我的RoutingContext和令牌,例如, vertxContext还是其他组件?

示例代码展示了我想要实现的目标:

Verticle cass

public class RestApiVerticle extends AbstractVerticle {

    businessLogicService service;

    @Override
    public void start() throws Exception {
        initService();

        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);

        JWTAuth authProvider = JWTAuth.create(vertx, getAuthConfig());
        router.route("/*").handler(JWTAuthHandler.create(authProvider));

        router.route("/somePath").handler(this::handleRequest);

        server.requestHandler(router::accept).listen(config().getInteger("port"));
    }

    private void handleRequest(RoutingContext context){
        service.doSomeBusinessLogic(); //I could pass context here, but I thing this is not a proper way to do it, as business logic should not know about RequestContext
    }

    private void initService(){
        ExternalAPICaller caller = new ExternalAPICaller(WebClient.create(vertx));
        service = new BusinessLogicService(caller);
    }

    private JsonObject getAuthConfig() {
        return new JsonObject();
    }
}

BusinessLogicService:

public class BusinessLogicService {
    ExternalAPICaller caller;

    public BusinessLogicService(ExternalAPICaller caller){
        this.caller = caller;
    }

    public void doSomeBusinessLogic(){
        caller.doSth();
    }
}

ExternalAPICaller:

public class ExternalAPICaller {     WebClient客户端;

public ExternalAPICaller(WebClient client){
    this.client = client;
}

public void doSth(){
    String TOKEN = null; // I would like to retrive here my token from some vertx component

    client.post("externalAPIpath")
        .putHeader("Authorization", "Bearer" + TOKEN)
        .send(ctx -> {
            //(..)
        });
}

}

2 个答案:

答案 0 :(得分:0)

我的实现是在JavaScript(Node.js / Express)中,但是我使用cookie将JWT发送给客户端。

res.cookie("auth", token);
return res.redirect(`http://localhost:3000/socialauthredirect`);

答案 1 :(得分:0)

当您调用业务逻辑方法时,您可以传递请求authorization标头值,因为它包含您未触及的jwt令牌。然后在您的Web客户端上添加一个带有该值的标头,当然名为authorization,您的令牌将转发到下一个服务。