请求安全页面时,RestTemplate不会因403或302错误而失败

时间:2015-09-08 10:19:45

标签: java spring-mvc spring-security resttemplate

我有使用spring-security 4.0.1和spring mvc 4.1.6的web应用程序。 对于视图页面“/ admin”和数据API“/ admin / api / properties”,它具有以下spring安全配置:

<http pattern="/admin.*" request-matcher="regex" auto-config="false">
    <intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
    <intercept-url pattern="/admin/api/.+" access="hasRole('ADMIN')"/>
    <logout logout-url="/admin/logout" success-handler-ref="customLogoutSuccessHandler"/>
    <form-login login-page="/admin/login" login-processing-url="/admin/login"
                authentication-success-handler-ref="customSuccessHandler"
                authentication-failure-handler-ref="customFailureHandler"/>
    <csrf disabled="true" />
</http>

这没关系。但现在我试图通过使用不同凭据的rest模板向“/ admin”和“/ admin / api / properties”发送请求来测试安全性。

private HttpStatus fetchAccessStatusForPage(String username, String password, String requestUrl) {
    HttpHeaders headers = new HttpHeaders();
    String token = username + ":" + password;
    String authorizationValue = "Base " + new String(Base64.encode(token.getBytes()));
    headers.add("Authorization", authorizationValue);
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
    HttpStatus resultCode;
    try {
        ResponseEntity<Object> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.GET, httpEntity, Object.class);
        resultCode = responseEntity.getStatusCode();
    } catch (HttpClientErrorException e) {
        resultCode = e.getStatusCode();
    }
    return resultCode;

但它总是给我200 OK状态代码,无论我给出什么凭据,无论我测试什么api。 我也尝试了以下(没有任何凭据),响应代码也是200 OK,因为某些原因。

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Object> httpEntity = new HttpEntity<>(headers);      
    ResponseEntity<String> responseEntity = restTemplate.exchange(adminPageUrl, HttpMethod.GET, httpEntity, String.class);

我错过了什么吗?为什么休息模板在403错误上失败或至少302在标题中的位置失败?

也尝试了以下方法,结果是相同的

    URL u = new URL(getPageUrl(page));
    HttpURLConnection huc = (HttpURLConnection) u.openConnection();
    String token = username + ":" + password;
    String authorizationValue = "Base " + new String(Base64.encode(token.getBytes()));
    huc.setRequestProperty("Authorization", authorizationValue);
    huc.setRequestMethod("GET");
    huc.connect();
    return huc.getResponseCode()

0 个答案:

没有答案