2011-09-30 1 views
6

나는 Spring-MVC 애플리케이션을 가지고있다. (즉, 나는 Spring의 dispatcher 서블릿을 사용하고있다). 또한 Spring Security를 ​​사용하여 사용자를 인증합니다. 나는 봄의 디스패처 서블릿을 사용하기 때문에 (내가 제대로 설명서를 이해하는 경우), 나는 RequestContextHolder을 사용할 수 있도록하기 위해 내 web.xml에AuthenticationSuccessHandler에서 RequestContextHolder 및 HttpServletRequest.getUserPrincipal()에 액세스하기

<listener> 
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> 
    </listener> 

를 선언 할 필요가 없습니다.

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler { 

    @Override 
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { 

     int timeout = 60*60; 

     //does work 
     request.getSession().setMaxInactiveInterval(timeout); //60 minutes 
     System.out.println("Session timeout of user: " + authentication.getName() + " has been set to: " + timeout + " seconds."); 

     /* 
     //does not work 
     session().setMaxInactiveInterval(timeout); //60 minutes 
     System.out.println("Session timeout of user: " + request.getUserPrincipal().getName() + " has been set to: " + timeout + " seconds."); 
     */ 

     //now restore the default work flow (SavedRequestAwareAuthenticationSuccessHandler is the default AuthenticationSuccessHandler that Spring uses, 
     // see: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/core-web-filters.html#form-login-flow-handling) 
     (new SavedRequestAwareAuthenticationSuccessHandler()).onAuthenticationSuccess(request, response, authentication); 
    } 

    public static HttpSession session() { 
     ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); 
     return attr.getRequest().getSession(true); // true == allow create 
    } 
} 

당신이은 위에서 언급 한 코드에서 RequestContextHolder.currentRequestAttributes()HttpServletRequest.getUserPrincipal()이 작동하지 않는 이유 (그들이 컨트롤러 내부에서 작업 않습니다) 설명 할 수 없습니다 :

내 질문은 인터페이스 org.springframework.security.web.authentication.AuthenticationSuccessHandler 내 구현을 의미?

감사합니다.

+0

어, 이미 'RequestContextHolder.currentRequestAttributes'(요청 메소드 매개 변수)가 있고 이미 인증 메소드 매개 변수 인 사용자가 있습니다. 비트 무의미한 질문. Btw, 주체를 제공하기 위해 요청을 래핑하는 것은 SecurityContextHolderAwareRequestFilter에서 이루어지며, 이는 Form-login 이후에 (따라서 성공 핸들러 이후에) 이루어진다. – MikeN

답변

4

스프링 보안은 필터 기반입니다. Spring Security가 처리되고 Spring 요청 컨텍스트가 설정되지 않았을 때 DispatcherServlet이 아직 호출되지 않았기 때문에 정의 된 RequestContextListener가 필요한 이유입니다.

+0

감사합니다. 이것은'RequestContextHolder.currentRequestAttributes()'부분에 응답합니다. 이제'RequestContextListener'의 코드를 보았습니다 만'request.getUserPrincipal()'을 볼 수 없으므로'UserPrincipal'은'request'에 어디에 저장됩니까? 그것은'onAuthenticationSuccess()'를 입력하기 전에 자동으로 저장되지 않습니다. 왜냐하면 그 메소드 내에서'NullPointerException'을 제공하기 때문입니다. 나는 실제로 다른 필터/디스패처 서블릿에서'UserPrincipal'이'request'에 저장된 것을 묻습니다. 그리고'onAuthenticationSuccess()'의'request'에서 그것을 읽을 수있는 리스너가 있습니까? – rapt

관련 문제