0

i'm working on an tokenValidationInterceptor , where a request for token validation is send to an other micro-service which communicate with keycloak and send an ok status or unautorazed status , then i add some logic to the prehandle function and that's all , when i try to test it, i get this error:

jakarta.servlet.ServletException: Request processing failed: org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : "false"
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1019) ~[spring-webmvc-6.0.9.jar:6.0.9]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914) ~[spring-webmvc-6.0.9.jar:6.0.9]

always get the same response unauthorized status with body false

i tested the verifyToken method in the first micro service separatly , and i t was working fine , i get ok status with body true .

TokenValidationInterceptor prehandle method

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        String verificationUrl = "http://localhost:8090/user/info?token=" + token;
        ResponseEntity<Boolean> verificationResponse = restTemplate.getForEntity(verificationUrl, Boolean.class);
        if (verificationResponse.getStatusCode() == HttpStatus.OK && verificationResponse.getBody() != null && verificationResponse.getBody()) {
            return true;
        } else {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

and for the verifyToken in the other micro-service

public ResponseEntity<?> verifyToken(String token) {
            String keycloakUrl = "http://localhost:8080/auth/realms/lbv-realm/protocol/openid-connect/userinfo";
            if (token != null) {
                HttpHeaders headers = new HttpHeaders();
                headers.setBearerAuth(token);
                HttpEntity<String> requestEntity = new HttpEntity<>(headers);
                RestTemplate restTemplate = new RestTemplate();
                try {
                    ResponseEntity<String> response = restTemplate.exchange(keycloakUrl, HttpMethod.GET, requestEntity, String.class);
                    HttpStatusCode statusCode = response.getStatusCode();
                    if (statusCode.is2xxSuccessful()) {
                        return ResponseEntity.status(HttpStatus.OK).body(true);
                    } else {
                        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(false);
                    }
                } catch (Exception ex) {
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(false);
                }
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(false);
            }
    }

0 Answers0