我将使用undertow作为我的HTTP库,并想要验证每个请求的JWT令牌和HTTP方法。我不想在每个
HttpHandler
中实现验证。这样做是否正确?
Handler.java
public abstract class Handler implements HttpHandler {
private HttpString[] methods;
Handler(HttpString... methods) {
this.methods = methods;
}
@Override
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
// verifying HTTP method
boolean verified = false;
for (HttpString method : methods) {
if (httpServerExchange.getRequestMethod().equals(method)) {
verified = true;
break;
}
}
if (!verified) {
// return http 405, cause: invalid HTTP method
httpServerExchange.setStatusCode(StatusCodes.METHOD_NOT_ALLOWED);
httpServerExchange.getResponseSender().send(Variables.Response.EMPTY);
}
// verifying JWT token
String jwt = httpServerExchange.getRequestHeaders().get("jwt", 0);
JWT.verifyToken(jwt)
.addListener(token -> {
if (token != null) {
handleVerifiedRequest(httpServerExchange, token);
} else {
// return http 400, cause: JWT invalid
httpServerExchange.setStatusCode(StatusCodes.UNAUTHORIZED);
httpServerExchange.getResponseSender().send(Variables.Errors.INVALID_JWT);
}
});
}
public abstract void handleVerifiedRequest(HttpServerExchange httpServerExchange, String Token);
}
HelloHandler.java
public class HelloHandler extends Handler {
public HelloHandler(HttpString... methods) {
super(methods);
}
@Override
public void handleVerifiedRequest(HttpServerExchange httpServerExchange, String Token) {
// .. do something
}
}