Я знаю, что этот вопрос задан раньше, однако я столкнулся с конкретной проблемой здесь.
Я использую spring security 3.1.3.
В моем веб-приложении есть 3 возможных случая входа:
- Войдите через страницу входа в систему: OK.
- Войдите через ограниченную страницу: ОК тоже.
- Вход через страницу с неограниченным доступом: не в порядке... Доступ к странице "Продукт" доступен всем, и пользователь может опубликовать комментарий, если он зарегистрировался. Таким образом, форма входа находится на той же странице, чтобы пользователи могли подключаться.
Проблема с случаем 3) заключается в том, что я не могу перенаправить пользователей на страницу "продукт". Они перенаправляются на домашнюю страницу после успешного входа в систему, несмотря ни на что.
Обратите внимание, что в случае 2) перенаправление на ограниченную страницу выполняется из окна после успешного входа в систему.
Вот соответствующая часть моего файла security.xml:
<!-- Authentication policy for the restricted page -->
<http use-expressions="true" auto-config="true" pattern="/restrictedPage/**">
<form-login login-page="/login/restrictedLogin" authentication-failure-handler-ref="authenticationFailureHandler" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<!-- Authentication policy for every page -->
<http use-expressions="true" auto-config="true">
<form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
<logout logout-url="/logout" logout-success-url="/" />
</http>
Я подозреваю, что "политика проверки подлинности для каждой страницы" отвечает за проблему. Однако, если я удалю его, я больше не могу войти... j_spring_security_check отправляет ошибку 404.
EDIT:
Благодаря Ральфу, я смог найти решение. Итак, вот что: я использовал свойство
<property name="useReferer" value="true"/>
что показал мне Ральф. После этого у меня возникла проблема с моим случаем 1): при регистрации на странице входа пользователь остался на той же странице (и не перенаправлялся на домашнюю страницу, как раньше). Код до этого этапа был следующим:
<!-- Authentication policy for login page -->
<http use-expressions="true" auto-config="true" pattern="/login/**">
<form-login login-page="/login" authentication-success-handler-ref="authenticationSuccessHandlerWithoutReferer" />
</http>
<!-- Authentication policy for every page -->
<http use-expressions="true" auto-config="true">
<form-login login-page="/login" authentication-failure-handler-ref="authenticationFailureHandler" />
<logout logout-url="/logout" logout-success-url="/" authentication-success-handler-ref="authenticationSuccessHandler"/>
</http>
<beans:bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<!-- After login, return to the last visited page -->
<beans:property name="useReferer" value="true" />
</beans:bean>
<beans:bean id="authenticationSuccessHandlerWithoutReferer" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<!-- After login, stay to the same page -->
<beans:property name="useReferer" value="false" />
</beans:bean>
Это должно работать, по крайней мере теоретически, но это не так. Я все еще не знаю, почему, поэтому, если у кого-то есть ответ на этот вопрос, я с радостью создам новую тему, чтобы он мог поделиться своим решением.
Тем временем я пришел к обходу. Не лучшее решение, но, как я уже сказал, если у кого-то есть что-то лучшее, чтобы показать, я все уши. Итак, это новая политика проверки подлинности для страницы входа:
<http use-expressions="true" auto-config="true" pattern="/login/**" >
<intercept-url pattern="/**" access="isAnonymous()" />
<access-denied-handler error-page="/"/>
</http>
Решение здесь довольно очевидно: страница входа в систему разрешена только для анонимных пользователей. Когда пользователь подключен, обработчик ошибок перенаправляет его на домашнюю страницу.
Я сделал несколько тестов, и все, кажется, работает хорошо.