Перенаправление после входа в систему (безопасность Spring в GAE)

У меня возникают проблемы с тем, чтобы мой логин всегда перенаправлялся в одно и то же место. Я сделал что-то вроде этого

<http auto-config="true" use-expressions="true" entry-point-ref="gaeEntryPoint" >
    <intercept-url pattern="/_ah/login" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <custom-filter position="PRE_AUTH_FILTER" ref="gaeFilter"/>
    <form-login authentication-success-handler-ref="authSuccessHandler"/>
</http>

<beans:bean id="authSuccessHandler"
            class="dk.lindhardt.arbejdsfordeling.server.security.AuthenticationSuccessHandlerImpl"/>

И

public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

   public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) 
   throws IOException, ServletException {
       if (authentication != null && authentication.isAuthenticated()) {
           response.sendRedirect(OrganizationListServlet.URL);
       }
   }

 }

Он никогда не попадает в этот метод выше. Как мне это сделать?

Изменить: я следовал этому руководству http://blog.springsource.com/2010/08/02/spring-security-in-google-app-engine/


person AnAmuser    schedule 01.03.2011    source источник
comment
Можете ли вы поделиться определением компонента вашего пользовательского фильтра (gaeFilter)?   -  person Sagar    schedule 08.03.2011


Ответы (4)


Вам не нужно иметь этот сервлет, который затем выполняет перенаправление. Вы можете иметь перенаправление в самой конфигурации.

<http auto-config="true">   
    <intercept-url pattern="/app/login" filters="none" />
    <form-login 
        login-page="/app/login" 
        login-processing-url="/app/dologin" 
        authentication-failure-url="/app/login?login_error=1" 
        default-target-url="/app/home"/>
</http>
person Scott    schedule 05.03.2011

Я думаю, мы можем расширить SimpleUrlAuthenticationSuccessHandler и вызвать метод super.onAuthenticationSuccess() для использования DefaultRedirectStrategy. Модифицированный код будет:

public class AuthenticationSuccessHandlerImpl extends SimpleUrlAuthenticationSuccessHandler {
       @Override
   public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) 
   throws IOException, ServletException {
       if (authentication != null) {
       setDefaultTargetUrl(OrganizationListServlet.URL);
              super.onAuthenticationSuccess(request, response, authentication);
       }

   }

 }
person Ritesh    schedule 07.03.2011
comment
SimpleUrlAuthenticationSuccessHandler — это класс, а не интерфейс, поэтому вам необходимо его расширить. - person Saurabh; 01.05.2013

Вы можете сделать это без обработчика, добавив «всегда использовать цель по умолчанию» в настройках формы входа в систему.

<form-login default-target-url='/your/target/url.htm' always-use-default-target='true' />

См. http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-form-and-basic в разделе «Установка назначения по умолчанию после входа в систему». "

person digitaljoel    schedule 01.03.2011
comment
Я уже пробовал это, но это не работает. Меня по-прежнему перенаправляют на страницу с ограниченным доступом, которую я пытался посетить. - person AnAmuser; 01.03.2011
comment
Если бы это был я, моим следующим тестом было бы попробовать это без пользовательской точки входа. Упрощайте, пока не заработает, затем вводите заново, пока не найдете причину проблемы. - person digitaljoel; 01.03.2011

Это некрасиво, но я решил эту проблему, поместив пользовательский фильтр в ПОСЛЕДНЮЮ позицию.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws
            IOException, ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

       if (authentication != null && authentication.isAuthenticated()) {
            User user = (User) authentication.getPrincipal();
            if (user.isLoggingIn()) {
                if (authentication.getAuthorities().contains(AppRole.ROLE_NEW_USER)) {
                    ((HttpServletResponse) response).sendRedirect(RegistrationServlet.URL);
                } else {
                    ((HttpServletResponse) response).sendRedirect("/" + OrganizationListServlet.URL);
                }
                user.setLoggingIn(false);
            } else if (user.isLoggingOut()) {
                ((HttpServletRequest) request).getSession().invalidate();
            }
        }
        filterChain.doFilter(request, response);
}

Я думаю, проблема в том, что gaeFilter обходит обычную процедуру входа в систему, и поэтому я не могу использовать обработчик аутентификации-успеха.

person AnAmuser    schedule 09.03.2011
comment
1. Я думаю, что это не элегантное решение. Как показано в blog.springsource.com/ 2010/08/02/ не существует такого понятия, как «обход обычной процедуры ведения журнала». В этом коде блога Люк Тейлор использовал failureHandler. Точно так же можно использовать successHandler. - person Ritesh; 10.03.2011
comment
Хорошо, я вижу, что это лучшее решение. - person AnAmuser; 10.03.2011
comment
Мой голос против заблокирован. Если вы отредактируете свой ответ, я с удовольствием удалю его. - person Ritesh; 11.03.2011
comment
user.isLoggingIn() не является методом - person coure2011; 11.07.2013