[英]Spring Security, Rest Authentication and CSRF
我想在我的應用程序中使用身份驗證。 我有一個Spring MVC應用程序和Spring Security應用程序。 對瀏覽器,它工作正常。 這意味着,我向我的應用程序驗證用戶並使用網頁。
現在,我想用休息。 我添加了不安全的控制器方法@ResponseBody,我在json中收到響應。 但是如何使用RestTemplate用戶和密碼連接到我的應用程序?
我在RestClient中的代碼是(用於測試):
public void unsecureProfileTest() {
String url = articleServiceUrl + "unsecure/profile/test.json";
url = articleServiceUrl + "secure/profile/wiew.json";
HttpEntity<Object> entity = new HttpEntity<Object>(getHeaders("user:userpassword"));
Object s = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
}
static HttpHeaders getHeaders(String auth) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON,
MediaType.TEXT_HTML));
byte[] encodedAuthorisation = Base64.encode(auth.getBytes());
headers.add("Authorization", "Basic "
+ new String(encodedAuthorisation));
return headers;
}
我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/*").permitAll().and()
.formLogin().successHandler(successHandler)
.defaultSuccessUrl("/").failureHandler(failureHandler)
.failureUrl("/login?error=true").permitAll().and().logout()
.permitAll();
http.authorizeRequests().antMatchers("/resources/**").permitAll();
http.authorizeRequests().antMatchers("/welcome").permitAll();
http.authorizeRequests().antMatchers("/unsecure/**").permitAll();
http.authorizeRequests().antMatchers("/secure/*").authenticated();
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
結果是:訪問被拒絕。 我想問題來自restTemplate的身份驗證,但我如何進行身份驗證?
我的第二個問題是關於csrf誰被禁用但我想啟用它(我的表單使用它)
我正在使用Spring 4.0和Spring Security 3.2
編輯我更新了我的代碼
String url = articleServiceUrl + "unsecure/profile/test.json";
url = articleServiceUrl + "secure/profile/wiew.json";
HttpEntity<Object> entity = new HttpEntity<Object>(getHeaders("{user:userpassword, password:userpassword}"));
Object s = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
我收到一個代碼302
編輯18022014 - 16:46我更新到
String url = articleServiceUrl + "login?username=user&password=userpassword";
HttpEntity entity restTemplate;exchange(url, HTTPMethod.POST,null, HttpEntity.class)
system.out.println(entity);
在Web服務器的日志中,我收到了一條成功消息(請參閱“user”的userdetails)。
現在,我想使用身份驗證來訪問其他URL(“secure / profile / view.json”)
如何保持身份驗證?
謝謝
我一直在玩spring security和spring boot REST應用程序,我創建了自己的MapCsrfTokenRepository ,而不是默認的HttpSessionCsrfTokenRepository 。
然后,您可以為其余的URI啟用csrf
http.csrf().csrfTokenRepository(tokenRepository)
主要思想是在使用GET的客戶端訪問/登錄資源時返回新的CSRF_TOKEN,因為GET不需要csrf令牌。 然后客戶端必須在下次調用中使用此令牌。
示例在github上
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.