2014-11-25 4 views
1

RestController에 인증을 추가하려고하는데 Java Configuration으로 좋은 설명서 나 샘플을 찾을 수 없습니다. Java 구성 + REST 인증을 사용하는 스프링 보안 방법 수준 보안?

나는이 시도하지만

내 컨트롤러가 @PreAuthorize

@RestController 
@RequestMapping("/api/hello") 
public class HelloController { 

    @RequestMapping(value = "/say", method = RequestMethod.GET) 
    public String sayHello() { 
     return "hello"; 
    } 

    @PreAuthorize("hasRole('ROLE_USER')") 
    @RequestMapping(value = "/say/user", method = RequestMethod.GET) 
    public String sayHelloWithUserProtection(){ 
     return "Hello USER"; 
    } 

    @PreAuthorize("hasRole('ROLE_ADMIN')") 
    @RequestMapping(value = "/say/admin", method = RequestMethod.GET) 
    public String sayHelloWithAdminrProtection(){ 
     return "Hello ADMIN"; 
    } 
} 

의 SecurityConfig

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
@ComponentScan(basePackages = {"com.test.server.security"}) 
public class SecurityConfig { 


    @Autowired 
    public void configureAuthentification(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
     .inMemoryAuthentication() 
       .withUser("user").password("password").roles("USER").and() 
       .withUser("admin").password("admin").roles("USER","ADMIN"); 
    } 

    @Configuration 
    public static class ApiWebConfigurerAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
        .antMatcher("/api/**") 
        .formLogin(); 
     } 
    } 

} 

SecurityWebApplicationInitializer의 주석을 붙일 수 있고 (내가 로그인없이 모든 요청에 ​​액세스 할 수 있습니다) 작동하지 않습니다

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { 
} 

어떻게 작동시킬 수 있습니까?

Java 구성으로 REST 토큰 기반 (세션 키 및 다른 사용자 정의 값 저장 토큰) 인증을 JPA (또는 JDBC?) 데이터베이스에 저장하는 좋은 지침이 있습니까?

답변

0

이 있는지 확인하십시오.

내 오류는 getServletConfigClasses() 대신 getRootConfigClasses()에 SecurityConfig를 넣었습니다. 이제 WebApplicationInitialization은 다음과 같이 보이며 훌륭하게 작동합니다!

public class WebApplicationInitialisation extends AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class[]{RootConfig.class}; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return new Class[]{WebMvcConfig.class, SecurityConfig.class}; 
    } 

    @Override 
    protected String[] getServletMappings() { 
     return new String[]{"/"}; 
    } 


    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     super.onStartup(servletContext); 
    } 
} 
+0

나는 그것을 얻지 못한다. 더 자세히 설명해 주겠다.?, web.xml에서 Spring config를 시작한다. – pazfernando

2

formLogin()을 삭제하십시오. REST가 무국적이라고 가정하는 사고 방식을 유지해야합니다. 이런 식으로 양식을 사용하여 로그인하는 것은 순전히 REST가 아닙니다.

이와 같이 스프링 보안 체인을 사용하여 정밀한 마스크 필터를 만들 수 있습니다 (무작위로 추가 한 항목 만 더 완전하게 만들 수 있습니다.) 스프링 보안은 필터로 작동합니다. 즉, 실제 필터를 생성해야합니다. 당신은 경로에 일치하기 전에 요청 권한을 부여해야합니다.

http.authorizeRequests() 
     .antMatchers("/login").permitAll() 
     .antMatchers("/say/user/").hasRole("USER") 
     .antMatchers("/say/admin").hasRole("ADMIN") 
     .anyRequest().authenticated(); 

위의 코드는 자기 설명해야한다. 그렇지 않으면, 나는 그것을 정교하게하려고합니다.

토큰 기반 로그인에 관해서는

는, 이것은이다 좋은 생각이지만, 자신의 것을 굴리지 말아야합니다. 봄에는 위대한 Oauth 지원과 g가 있습니다. 그것으로 REST API를 안전하게 보호하기 시작했습니다.

이 자습서에서는이 API에 대해 자세히 설명하고 더 나은 API를 개발하는 데 도움이됩니다. http://spring.io/guides/tutorials/bookmarks/

또한 당신은 내가 질문에 내 WebApplicationInitialisation을 넣어 깜빡 여기 REST에 파울러의 글에서 살펴 http://martinfowler.com/articles/richardsonMaturityModel.html

+0

답변 해 주신 데 대해 감사 드리며 OAuth를 알려 드리겠습니다. 이 자습서는 http://jaxenter.com/rest-api-spring-java-8-112289.html에 있습니다. 그러나 antMatchers 대신 @PreAuthorize를 사용할 방법이 없습니까? (나는 유지 관리가 더 쉽다고 생각한다.) – alvinmeimoun

+0

둘 다 사용할 수 있지만 antMatchers는 무시하지 않을 것이다. – scav