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

huangapple go评论101阅读模式
英文:

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

问题

我正在开发一个tokenValidationInterceptor,其中会向另一个微服务发送令牌验证请求,该微服务与Keycloak通信并返回正常状态或未授权状态。然后,我在prehandle函数中添加了一些逻辑,就是这样。当我尝试测试它时,我得到了这个错误:

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

TokenValidationInterceptor的preHandle方法:

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

}

另一个微服务中的令牌验证:

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

请注意,我已经将HTML编码的引号(&quot;)更改为普通的双引号(")以便于代码的理解。

英文:

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 &quot;org.springframework.web.client.RestTemplate.getForEntity(String, java.lang.Class, Object[])&quot; because &quot;this.restTemplate&quot; is null

TokenValidationInterceptor prehandle method

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        String verificationUrl = &quot;http://localhost:8090/user/info?token=&quot; + token;
        ResponseEntity&lt;Boolean&gt; verificationResponse = restTemplate.getForEntity(verificationUrl, Boolean.class);
        if (verificationResponse.getStatusCode() == HttpStatus.OK &amp;&amp; verificationResponse.getBody() != null &amp;&amp; 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&lt;?&gt; verifyToken(String token) {
            String keycloakUrl = &quot;http://localhost:8080/auth/realms/lbv-realm/protocol/openid-connect/userinfo&quot;;
            if (token != null) {
                HttpHeaders headers = new HttpHeaders();
                headers.setBearerAuth(token);
                HttpEntity&lt;String&gt; requestEntity = new HttpEntity&lt;&gt;(headers);
                RestTemplate restTemplate = new RestTemplate();
                try {
                    ResponseEntity&lt;String&gt; 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);
            }
    }

答案1

得分: 0

如果您的 restTemplate 为null,您可以通过构造函数或 @Autowired 注解来简单地注入 RestTemplate

@Autowired
private RestTemplate restTemplate;

或者

public class YourClass {

    private final RestTemplate restTemplate;

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

}
英文:

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

}

huangapple
  • 本文由 发表于 2023年7月13日 18:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定