2014-02-18 3 views
5

내 응용 프로그램에서 인증을 사용하고 싶습니다. 스프링 MVC 애플리케이션과 스프링 보안이 적용되었습니다. 브라우저에 대해 잘 작동합니다. 즉, 내 앱을 인증하고 웹 페이지를 사용한다는 의미입니다.스프링 보안, 휴식 인증 및 CSRF

이제 나머지를 사용하고 싶습니다. 내 비보안 컨트롤러 메서드 @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; 
} 

내의 SecurityConfig :

@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에 관한되지만 내가 (내 양식 사용) 나는 스프링 4.0과 스프링 시큐리티 3.2

편집 I을 사용하고

을 활성화하려면 내가 코드 302

을받을

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

내 코드 업데이트

편집은 18,022,014 - 16시 46분 나는 웹 서버의 로그에

String url = articleServiceUrl + "login?username=user&password=userpassword"; 
HttpEntity entity restTemplate;exchange(url, HTTPMethod.POST,null, HttpEntity.class) 
system.out.println(entity); 

업데이트, 나는 성공 메시지 ("사용자"에 된 UserDetails 참조) 받았다.

지금, 나는 사용 인증이 다른 URL로 접근하려는

어떻게 인증을 유지하기 위해 ("프로필/view.json/보안")? 나는 봄 보안 및 봄 부팅 REST 응용 프로그램과 함께 연주 한

+0

github

예이다. 대신 기본 인증과 같은 것을 사용해보십시오. –

+0

사용자를 관리 할 웹 사이트가있어서 관리자가 작성한 많은 것들이 있기 때문에 대화식 로그인이 있습니다 –

+0

예,하지만이 질문에서 말하는 ReST API와는 별개의 문제일까요? 가장 좋은 방법은 아마도 ReST 부분을위한 별도의 상태 비 저장 필터 체인을 정의하는 것입니다. 양식 로그인 구성은 기본 인증 헤더를 처리하지 않습니다. –

답변

2

당신을 감사하고 내가 대신 기본 HttpSessionCsrfTokenRepository의 사용 내 자신의 MapCsrfTokenRepository를 만들었습니다. 더 CSRF 토큰이 GET 필요하지 않기 때문에

그런 다음 당신은 주요 아이디어는 와 클라이언트 액세스 /로그인 자원을 얻을 때 새로운 CSRF_TOKEN을 반환하는 것입니다

http.csrf().csrfTokenRepository(tokenRepository) 

으로 나머지 URI에 대한 CSRF를 활성화 할 수 있습니다 . 그리고 클라이언트는 다음 호출에서이 토큰을 사용해야합니다.폼 기반 인증을 사용하면 대화 형 로그인 (잠재적으로 어떤 세션)이없는 좋은 선택이 아니다

+0

안녕하세요 bsmk. 토큰을 리포지토리에 저장하면 어떻게하면 안심할 수 있습니까? – Jaxox

+0

완전히 안정되지 않았습니다. 그것은 단지 트레이드 오프 일뿐입니다. 이것이 올바른 접근인지 확실하지 않지만 다른 것을 찾지 못했습니다. – bsmk