Search code examples
javaspring-bootmicroserviceskeycloakspring-resttemplate

Cannot invoke"org.springframework.web.client.RestTemplate.getForEntity(String, java.lang.Class, Object[])""this.restTemplate"null


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 :

java.lang.NullPointerException: Cannot invoke "org.springframework.web.client.RestTemplate.getForEntity(String, java.lang.Class, Object[])" because "this.restTemplate" is null

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;
        }
    }

Appconfig

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor( new TokenValidationInterceptor());
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

and for the tokenValidation 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);
            }
    }

Solution

  • If your restTemplate is null,you can simply inject RestTemplate through constructor or @Autowired annotation.

    @Autowired
    private RestTemplate restTemplate;
    

    or

    public class YourClass{
    
    private final RestTemplate restTemplate;
    
    public YourClass(RestTemplate restTemplate){
    this.restTemplate=restTemplate;
    }
    
    }