使用HTTP POST方法,该方法在春季使用基本身份验证进行保护



我想使用一个使用 basicAuth 保护的 post 方法。我正在使用springBoot,Spring RestTemplate来使用它。

我试过这样:

@CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/ValidateAnswers", method = RequestMethod.POST)
    public ResponseEntity<String> ValidateAnswers(@RequestBody Object requestIbject,
            HttpServletRequest request, HttpServletResponse response) {
        final String uri = "foo:8080//validateAnswers";
// hiding full path here, 
        RestTemplate restTemplate = new RestTemplate();
        String plainClientCredentials = "user:pass";
        String base64ClientCredentials = new String(
                Base64.encodeBase64(plainClientCredentials.getBytes()));
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64ClientCredentials);
        HttpEntity<String> entity = new HttpEntity<String>("parameters",
                headers);
        ResponseEntity<String> respEntity = restTemplate.postForObject(uri, requestIbject, String.class);
//              .exchange(uri,
//              HttpMethod.POST, entity, String.class);
        System.err.println("=------------Response--------------");
        System.err.println("----" + respEntity);
        return respEntity;
    }

如何使用基本身份验证和后请求正文传递标头?

如果您使用 Spring> 4.3.1

RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

从您的代码片段来看,我认为您不应该使用post方法,请先尝试get。并参考我之前的测试:

public class Test {  
    private HttpHeaders getHeaders(){  
        String plainCredentials="admin:admin";  
        String base64Credentials = Base64.getEncoder().encodeToString(plainCredentials.getBytes());  
        HttpHeaders headers = new HttpHeaders();  
        headers.add("Authorization", "Basic " + base64Credentials);  
        return headers;  
    }  
    @Test  
    public void testLogin() {  
        RestTemplate restTemplate = new RestTemplate();  
        HttpEntity<String> request = new HttpEntity<String>(getHeaders());  
        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/login", HttpMethod.GET,  
                request, String.class);  
        System.out.println(response.getBody());  
    }  
}  

相关内容

  • 没有找到相关文章

最新更新