2014-10-13 2 views
2

스프링 보안에 XML 기반 설정을 사용하고 싶습니다. 첫 번째 아이디어는 사용자 암호에 SHA-256 또는 다른 해싱 함수를 사용하는 것이 었습니다. 나는 이것을 일반 자바로 해결할 수있는 좋은 방법을 찾을 수 없었다. 그래서 나는 XML로 구성하기 시작했다. 그것이 재미있는 시점이었습니다.스프링 부트에서 스프링 보안의 XML 설정

내 구성 : 8.0.8 :

  • 봄 부팅 * 1.1.8.RELEASE
  • 스프링 부팅 도입 - 바람둥이 - 포함 - 재스퍼
  • 1.1.8에서

    스프링 security.xml :

    <beans:beans xmlns="http://www.springframework.org/schema/security" 
          xmlns:beans="http://www.springframework.org/schema/beans" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
          xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
          http://www.springframework.org/schema/security 
          http://www.springframework.org/schema/security/spring-security.xsd> 
    
        <http pattern="/css/**" security="none"/> 
        <http pattern="/login.html*" security="none"/> 
    
        <http> 
         <intercept-url pattern="/**" access="ROLE_USER" /> 
         <form-login login-page='/login.html'/> 
        </http> 
    
        <authentication-manager> 
    
         <authentication-provider> 
          <user-service> 
           <user name="admin" password="admin" 
             authorities="ROLE_USER, ROLE_ADMIN"/> 
           <user name="bob" password="bob" 
             authorities="ROLE_USER"/> 
          </user-service> 
         </authentication-provider> 
        </authentication-manager> 
    
    </beans:beans> 
    

    내가 XML을로드 public static void main 찾을 수 클래스에 파일 :

    @Configuration 
    @ComponentScan 
    @EnableAutoConfiguration 
    @Order(HIGHEST_PRECEDENCE) 
    @ImportResource({ 
         "/spring-security.xml" 
    }) 
    public class PhrobeBootApplication extends SpringBootServletInitializer { 
    ... 
    } 
    

    그러나 나는 어떤 pageload에 다음과 같은 예외를 얻을 :

    [ERROR] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception 
    org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext 
    ... 
    

    따라서이 경우,로드하지 않습니다 resources/WEB-INF/web.xml에서 구성처럼 보인다 나는 좋은 것을 가지고있다. understanding from the documentation, 부팅하지 않고 그냥 봄을 사용할 때 사용해야한다. (필터를 구성해야합니다). 내가 맞습니까?

    왜이 오류가 발생합니까? 스프링 부트에서 봄 보안을위한 xml 기반 구성을 사용하는 더 좋은 방법이 있습니까? web.xml도 tomcat으로로드합니까?

답변

0

스프링 부트의 최근 버전에서 Dave Syer의 진술에 따르면 스프링 보안을 구성하는 가장 좋은 방법은 Java 구성입니다.

SHA-256 인코더가 필요했지만 구현하기위한 간단하고 우수한 솔루션을 찾지 못했습니다. passwordEncoder를 사용하여 jdbcAuthentication을 구성하기 만하면됩니다. 이 정말 정말 간단하다 :

@EnableWebSecurity 
public class SpringSecurityConfigurer extends WebMvcConfigurerAdapter { 

    @Override 
    public void addViewControllers(ViewControllerRegistry registry) { 
     registry.addViewController("/login").setViewName("login"); 
    } 

    @Bean 
    public ApplicationSecurity applicationSecurity() { 
     return new ApplicationSecurity(); 
    } 

    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
    protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter { 

     @Autowired 
     private SecurityProperties security; 

     @Autowired 
     private DataSource dataSource; 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest().fullyAuthenticated() 
        .and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll() 
        .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login"); 
     } 

     PasswordEncoder sha256PasswordEncoder = new PasswordEncoder() { 
      @Override 
      public String encode(CharSequence rawPassword) { 
       return Hashing.sha256().hashString(rawPassword, Charsets.UTF_8).toString(); 
      } 

      @Override 
      public boolean matches(CharSequence rawPassword, String encodedPassword) { 
       return encodedPassword.equals(Hashing.sha256().hashString(rawPassword, Charsets.UTF_8).toString()); 
      } 
     }; 

     @Override 
     public void configure(AuthenticationManagerBuilder auth) throws Exception { 
      auth.jdbcAuthentication() 
        .dataSource(this.dataSource) 
        .passwordEncoder(sha256PasswordEncoder); 
     } 

    } 

} 
0

Java 구성으로 수행 할 수있는 작업이 없기 때문에이 작업을 시도하지는 않았지만 제공되는 WebSecurityConfigurers (및 @EnableWebSecurity)을 제거해야합니다. 나는 그렇게하는 것이 XML보다 더 복잡 할 것이라고 생각한다. (그러나 XML을 사용할 필요가 없다. @EnableAutoConfiguration에서 SecurityAutoConfiguration을 제외하고 문제가 발생하면 처리해야합니다 (예를 들어, SecurityProperties 유형의 bean이 필요할 수 있으며, 더 많은 문제를 일으키지 않으면 액츄에이터를 사용할 수 없습니다).

"구성에서 resources/WEB-INF/web.xml"에 대한 의미가 확실하지 않습니다. a) 스프링 부트 앱이고 b)없는 경우에도 resources/WEB-INF/web.xml이 아닙니다.

+0

Java에서 비밀번호 인코딩 (예 : sha256)을 구성하는 방법을 알고 싶습니다. 나는 매뉴얼에서 그것에 대해 아무것도 발견 할 수 없다. 방금 XML을 사용하여 가능한 솔루션을 제공하려고했습니다. – zeal

+0

web.xml 정보 : 프로젝트에서 tomcat을 사용합니다. 웹 컨테이너로 web.xml을 사용하여 구성 할 수 있습니다. 스프링 보안 문서에는이 conf의 사용에 대한 언급이 있습니다. http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#ns-web-xml – zeal

+0

btw thanks 대답은. 암호로 인코딩을 구성하는 프로그래밍 방식을 갖고 싶습니다. :). 방법이 있다면 스프링 부트 문서에서 언급해야합니다. – zeal

1

저도 같은 문제를 얻고 있었다 후 나는 XML 파일의 경로를 변경하고 src/main/resources/spring에로 유지했다. 괜찮 았어.

@SpringBootApplication 

@ImportResource("classpath:/spring/spring-security.xml") 
+0

이 대답에 동의하십시오. 봄 부팅 구성은 자바 클래스 중심입니다. 그러나 구성의 일부는 여전히 XML 기반 일 수 있습니다. @ImportResource와 함께 XML의 @Configuration 클래스 중심 사용을 참조하십시오 (http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java-combining-java-centric).). – Hong

관련 문제