2016-11-02 3 views
1

스프링 보안을 사용하고 있으며 사용자 성공 로그인 후 세션에 User 개체를 시작하고 싶습니다.Spring에서 AuthenticationSuccessHandler의 세션 범위 bean이 작동하지 않습니다.

보안 구성은 아래와 같다 :

@Configuration 
@EnableWebSecurity 
@PropertySource("classpath://configs.properties") 
public class SecurityContextConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private Environment env; 

    @Autowired 
    SimpleUrlAuthenticationSuccessHandler simpleUrlAuthenticationSuccessHandler; 


    @Autowired 
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { 

     auth.inMemoryAuthentication() 
      .withUser(env.getProperty("security.user1.userid")) 
      .password(env.getProperty("security.user1.pass")) 
      .roles(env.getProperty("security.user1.role")); 
    } 


    @Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http.authorizeRequests().antMatchers("/*.cm") 
       .access("hasRole('ADMIN')") 
       .and() 
       .formLogin() 
        .loginPage("/public-page.cm") 
        .loginProcessingUrl("/j_spring_security_check") 
        .usernameParameter("j_username") 
        .passwordParameter("j_password") 
        .successHandler(simpleUrlAuthenticationSuccessHandler) 
        .failureUrl("/public-page-authentication-failure.cm") 
       .and() 
        .logout() 
        .logoutSuccessUrl("/public-page.cm") 
        .invalidateHttpSession(true) 
        .logoutUrl("/j_spring_security_logout") 
       .and() 
        .csrf().disable(); 

    } 

    /** 
    * configure which patterns the spring security should not be applied 
    */ 
    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.ignoring().antMatchers("/index.jsp", "/public-page.jsp", "/public-page.cm", 
       "/public-page-authentication-failure.cm", "/images/**", "/css/**", "/js/**"); 
    } 

} 

User

@Component 
@Scope("session") 
public class User { 

    private String selectedSystem; 
    private String selectedBank; 

}

SimpleUrlAuthenticationSuccessHandler이다 :

@Component 
public class SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { 
    protected Log logger = LogFactory.getLog(this.getClass()); 

    @Autowired 
    private User user; 

오류 : 나는 How to retrieve a session-scoped bean inside AuthenticationSuccessHandler?을 읽고하지만 Autowire 없음을하려고하면 그것이

도움이되지 않습니다

public class WebAppInitializer implements WebApplicationInitializer { 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext(); 
     appContext.register(DatabaseContextConfig.class); 


     servletContext.addListener(new ContextLoaderListener(appContext)); 
     servletContext.addListener(new RequestContextListener()); 

     //Add Spring security filter 
     FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter(
       AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME, DelegatingFilterProxy.class); 
     springSecurityFilterChain.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); 

    } 

} 

:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:355) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) 

나는 다음과 같이 웹 응용 프로그램에 RequestContextListener을 추가 한 세션 빈, 잘 작동합니다.

문제를 해결하는 방법을 알려주세요.

답변

1

예외는 세션 범위를 지정한 사용자 bean에 대한 것입니다. 세션 범위에 대한 일부 구성을 놓친 것 같습니다.

스프링 MVC에서는 웹 응용 프로그램 컨텍스트로 작업하기 때문에 추가 범위가 있습니다. 추가 범위는 세션 범위, 요청 범위, 응용 프로그램 범위입니다.

필자는 XML 구성을 사용하므로 내 답변이 해당 형식이되므로 나중에 Java 구성으로 변환 할 수 있습니다. 은 web.xml에서

당신이 그런 식으로, 리스너를 추가해야합니다 :.

이 리스너는 각 요청에 연결됩니다
<listener> 
     <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 
</listener> 

이 들어오는

을 지금, 당신의 빈과 함께하는 당신을 세션 범위를 갖고 싶어, 당신은 당신이 당신의 구성 파일에 AOP 네임 스페이스를 추가해야합니다 그렇게하기 위해, 그것에 범위의 프록시를 추가해야하고 있습니다 :

<bean class="user.package.User" scope="session"> 
    <aop:scoped-proxy/> 
</bean> 

이 빈을한다 일에 있으라. e dispatcher-servlet.xml 파일

모든 설정이 완료되었습니다.

난 콩라는 이름의 '사용자가'형이 될 것으로 예상된다 **이 오류에 직면 서버를 시작하는 동안

Spring JavaConfig of aop:scoped proxy

+0

[user.package : 자바 구성 범위 - 프록시를 사용하는 방법에 여기에

봐 .User]하지만 실제로는 유형이 [com.sun.proxy. $ Proxy36] ** –

+0

입니다. 실제로 user.package.User를 사용한다는 의미는 아니며 대신 패키지를 사용해야합니다. User 클래스가 bla.bla의 패키지 내에있는 경우.foo 다음 bla.bla.foo를 사용하십시오. 사용자 –

+0

물론 내 패키지를 사용했습니다. 그것은 오류가 '사용자'콩에 대한 프록시 모드를 설정하는 것 같습니다 –

관련 문제