EzyHTTP Request Interceptor

Updated at 1699803841000

EzyHTTP Request Inteceptor

Every request to EzyHTTP will be pass interceptors. You can define one or multipe interceptors for logging, authentication or any purposes.

1. Interceptor for logging

You can define an interceptor with a logger for logging purpose like this:

    @Interceptor
    public class LogRequestInterceptor
            extends EzyLoggable
            implements RequestInterceptor {
        @Override
        public boolean preHandle(RequestArguments arguments, Method handler) throws Exception {
            // you can remove this method if you don't need do anything
            return true;
        }
        @Override
        public void postHandle(RequestArguments arguments, Method handler) {
            logger.info(
                "request: {}, response: {}",
                arguments.getRequest().getRequestURI(),
                arguments.getResponse().getStatus()
            );
        }
    }

2. Interceptor for authentication

EzyHTTP provides @Authenticated annotation. You can use this annotation to any controllers or controller's methods, then EzyHTTP will know which APIs are mapping to the controllers or methods is authenticated. So you can use RequestURIManager.isAuthenticatedURI and interceptor to authencated client's requests like this:

    @Interceptor
    @AllArgsConstructor
    public class AuthenticationInterceptor extends EzyLoggable implements RequestInterceptor {
        private final RequestURIManager requestUriManager;
        private final IAuthenticationService authenticationService;
        @Override
        public boolean preHandle(RequestArguments arguments, Method handler) throws Exception {
            logger.info("request uri: {}", arguments.getRequest().getRequestURI());
            final HttpMethod method = arguments.getMethod();
            final String uri = arguments.getUriTemplate();
            if (!requestUriManager.isAuthenticatedURI(method, uri)) {
                return true;
            }
            String accessToken = arguments.getParameter("accessToken");
            if (accessToken == null) {
                accessToken = arguments.getHeader("accessToken");
            }
            if (accessToken == null) {
                accessToken = arguments.getCookieValue("accessToken");
            }
            if (accessToken == null) {
                throw new TokenNotFoundException("Can not get accessToken from cookie");
            }
            final long userId = authenticationService.verifyAccessToken(accessToken);
            arguments.setArgument(UserId.class, userId);
            return true;
        }
    }

3. Next

You can take a look Request Arguments