Search code examples
javacsrfvert.xcsrf-protection

Vert.x check if request header contains X-Requested-With and deny if not contains


In vert.x I want to deny requests if "X-Requested-With" header not exists in header. I want to do this for CSRF protection? I couldn't find a good document abour this. Anyone has an idea?


Solution

  • You can do that in routes handling:

        Router router = Router.router(vertx);
        router.route("/api/*").handler(event -> {
            if(event.request().getHeader("X-Requested-With") == null){
                event.response().setStatusCode(403).putHeader("content-type", "application/json; charset=utf-8").end("{\"message\":\"Not authorized\"}");
            }else{
                event.next();
            }
        });