Проблема аналогична: Spring Security 3.1 перенаправляет логин, не работает
Я использую Spring 3.1 с Spring Mvc и Spring Security.
Здесь app-security-config.
<security:http auto-config="true" use-expressions="true">
<security:form-login login-page="/login.jsp"
login-processing-url="/j_spring_security_check"
default-target-url="/pages/index.jsp"
always-use-default-target="true"
authentication-failure-url="/login.jsp?login_error=1"/>
<security:access-denied-handler ref="accessDeniedHandler"/>
<!-- Session Invalida-->
<security:logout invalidate-session="true" logout-success-url="/login.jsp" delete-cookies="JSESSIONID" />
<!-- Interceptadores -->
<!-- security:intercept-url pattern="/expire.jsp*" filters="none"/-->
<!-- security:intercept-url pattern="/login.jsp*" access="ROLE_ANONYMOUS" requires-channel="https"/-->
<security:intercept-url pattern="/expire.jsp" access="permitAll" />
<security:intercept-url pattern="/AccessDenied.jsp*" access="permitAll" />
<security:intercept-url pattern="/scripts/*" access="permitAll" />
<security:intercept-url pattern="/styles/*" access="permitAll" />
<security:intercept-url pattern="/images/*" access="permitAll" />
<security:intercept-url pattern="/login.jsp" access="permitAll" requires-channel="https"/>
<security:intercept-url pattern="/pages/**" access="hasAnyRole(${role.autenticated})" requires-channel="https"/>
<security:http-basic/>
<!-- Establece maximas sesiones para un usuarios -->
<security:session-management session-fixation-protection="none" >
<security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</security:session-management>
<!-- Establece maximas sesiones para un usuarios -->
<!-- security:session-management invalid-session-url="/expire.jsp" session-fixation-protection="none" >
<security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/expire.jsp"/>
</security:session-management-->
<!-- security:session-management invalid-session-url="/login.jsp?login_error=2" session-authentication-error-url="/login.jsp?login_error=3" session-fixation-protection="none" >
<security:concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login.jsp?login_error=4"/>
</security:session-management-->
<security:port-mappings>
<security:port-mapping http='8080' https="8443"/>
</security:port-mappings>
</security:http>
<beans:bean id="accessDeniedHandler" class="ar.com.firstdata.upploader.web.mvc.controller.AccessDeniedController">
<beans:property name="accessDeniedUrl" value="/AccessDenied.jsp"> </beans:property>
</beans:bean>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/spring/*-config.xml</param-value>
</context-param>
<jsp-config>
<taglib>
<taglib-uri>sitemesh-page</taglib-uri>
<taglib-location>/tld/sitemesh-page.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>sitemesh-decorator</taglib-uri>
<taglib-location>/tld/sitemesh-decorator.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/META-INF/spring.tld</taglib-location>
</taglib>
</jsp-config>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- SiteMesh -->
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.app</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
Проблема возникает только при попытке получить доступ к некоторому действию, заканчивающему вызов метода контроллера:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/pages/findConfData.app">configurationController</prop>
<prop key="/pages/readLoadXML.app">configurationController</prop>
<prop key="/pages/addElementToList.app">configurationController</prop>
<prop key="/pages/eraseElementToList.app">configurationController</prop>
<prop key="/pages/persistXMLfiletransfer.app">configurationController</prop>
<prop key="/pages/findLoggedUser.app">configurationController</prop>
</props>
</property>
</bean>
и, как я говорю, поведение похоже на поведение, описанное в @spauny, в журнале появляется: "Доступ запрещен (пользователь анонимный), перенаправление на точку входа аутентификации", после AccessDeniedException и ничего не происходит...
Это такая ситуация: если я потрачу время, указанное в web.xml
<session-config>
<session-timeout>1</session-timeout>
</session-config>
и я вызываю страницу с ограничениями (в разделе "/pages/**") перенаправляет меня на страницу входа в систему... НО, когда вы пытаетесь вызвать какое-либо действие, которое заканчивается вызовом метода контроллера -suppose, удалите строку в [CN10 ]
<prop key="/pages/eraseElementToList.app">configurationController</prop>
@RequestMapping(method = RequestMethod.POST)
public final ModelAndView eraseElementToList(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Я просто получаю исключение ActionDenied в журнале и что он... не перенаправляет меня на страницу входа.
Обновление 1 04/25 19:43:27 DEBUG hannel.ChannelProcessingFilter - Request: FilterInvocation: URL: /pages/persistXMLfiletransfer.app; ConfigAttributes: [REQUIRES_SECURE_CHANNEL] 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 2 из 12 в дополнительной цепочке фильтров; firing Filter: 'ConcurrentSessionFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 3 из 12 в дополнительной цепочке фильтров; firing Filter: 'SecurityContextPersistenceFilter' 04/25 19:43:27 DEBUG ssionSecurityContextRepository - HttpSession возвратил нулевой объект для SPRING_SECURITY_CONTEXT 04/25 19:43:27 DEBUG ssionSecurityContextRepository - Нет SecurityContext был доступен из HttpSession: org.apache.catalina.session. StandardSessionFacade @521f809b. Будет создан новый. 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 4 из 12 в дополнительной цепочке фильтров; firing Filter: 'LogoutFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 5 из 12 в дополнительной цепочке фильтров; firing Filter: 'UsernamePasswordAuthenticationFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 6 из 12 в дополнительной цепочке фильтров; firing Filter: 'BasicAuthenticationFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 7 из 12 в дополнительной цепочке фильтров; firing Filter: 'RequestCacheAwareFilter' 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - pathInfo: both null (свойство equals) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - queryString: оба значения null (свойство равно) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - requestURI: arg1 =/UppAudioFilesWebApp/pages/persistXMLfiletransfer.app; arg2 =/UppAudioFilesWebApp/pages/persistXMLfiletransfer.app (свойство equals) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - serverPort: arg1 = 8443; arg2 = 8443 (свойство равно) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - requestURL: arg1 =/UppAudioFilesWebApp/pages/persistXMLfiletransfer.app; arg2 =/UppAudioFilesWebApp/pages/persistXMLfiletransfer.app (свойство equals) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - схема: arg1 = https; arg2 = https (свойство равно) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - serverName: arg1 = localhst; arg2 = localhst (свойство равно) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - contextPath: arg1 =/UppAudioFilesWebApp; arg2 =/UppAudioFilesWebApp (свойство equals) 04/25 19:43:27 DEBUG vedrequest.DefaultSavedRequest - servletPath: arg1 =/pages/persistXMLfiletransfer.app; arg2 =/pages/persistXMLfiletransfer.app (свойство equals) 04/25 19:43:27 DEBUG equest.HttpSessionRequestCache - удаление DefaultSavedRequest из сеанса, если присутствует 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 8 из 12 в дополнительной цепочке фильтров; firing Filter: 'SecurityContextHolderAwareRequestFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 9 из 12 в дополнительной цепочке фильтров; firing Filter: 'AnonymousAuthenticationFilter' 04/25 19:43:27 DEBUG.AnonymousAuthenticationFilter - заполненный SecurityContextHolder с анонимным токеном: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Учетные данные: [ЗАЩИТА]; Authenticated: true; Подробности: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0: 0: 0: 0: 0: 0: 0: 1; SessionId: 63C5BB1C1CD8981AAF23D71C5521FB9B; Предоставленные полномочия: ROLE_ANONYMOUS '04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 10 из 12 в дополнительной цепочке фильтров; firing Filter: 'SessionManagementFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 11 из 12 в дополнительной цепочке фильтров; firing Filter: 'ExceptionTranslationFilter' 04/25 19:43:27 DEBUG.security.web.FilterChainProxy -/pages/persistXMLfiletransfer.app в позиции 12 из 12 в дополнительной цепочке фильтров; firing Filter: 'FilterSecurityInterceptor' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/expire.jsp' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/accessdenied.jsp*' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/scripts/' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/styles/' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/images/*' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/login.jsp' 04/25 19:43:27 DEBUG web.util.AntPathRequestMatcher - проверка соответствия запроса: '/pages/persistxmlfiletransfer.app'; против '/pages/**' 04/25 19:43:27 DEBUG cept.FilterSecurityInterceptor - Защищенный объект: FilterInvocation: URL: /pages/persistXMLfiletransfer.app; Атрибуты: [hasAnyRole ('ROLE_TOMCAT', 'ROLE_ADMNI')] 04/25 19:43:27 DEBUG cept.FilterSecurityInterceptor - ранее аутентифицированный: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Учетные данные: [ЗАЩИТА]; Authenticated: true; Подробности: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0: 0: 0: 0: 0: 0: 0: 1; SessionId: 63C5BB1C1CD8981AAF23D71C5521FB9B; Предоставленные полномочия: ROLE_ANONYMOUS 04/25 19:43:27 DEBUG y.access.vote.AffirmativeBased - Избиратель: org.springframework.security.web.access.expression.WebExpressionVoter@1304ff98, возвращается: -1 04/25 19:43: 27 DEBUG ess.ExceptionTranslationFilter - доступ запрещен (пользователь анонимен); перенаправление на точку входа аутентификации org.springframework.security.access.AccessDeniedException: доступ запрещен в org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) в org.springframework.security.access.intercept. AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:205) в org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:114) в org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter( FilterSecurityInterceptor.java:83) в org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323) в org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) в org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323) в org.springframework.security.web.session.SessionManagementFilter.doFilter(Se ssionManagementFilter.java:101) в org.springframework.security.web.FilterChainProxy $ VirtualFilterChain.doFilter(FilterChainProxy.java:323) в org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
Наиболее вероятное объяснение здесь заключается в том, что у вас есть Spring ExceptionHandler
который захватывает AccessDeniedException
и предотвращает действие Spring Security. Это довольно распространенная проблема, если вы где-то используете защищенные аннотации (хотя вы не упомянули об этом нигде в своем вопросе).
Также должно быть ясно, из stacktrace, который упоминает исключение, что он не обрабатывается Spring Security (всегда выставлять stacktrace). Кроме того, пожалуйста, повторите проверку журнала более тщательно, чтобы провести различие между этими двумя случаями. Если вы видите "перенаправление на точку входа в аутентификацию", значит, Spring Security получает исключение, и вы должны увидеть страницу входа в систему. Вы не увидите этого, если используется обработчик исключений.
Если это проблема, вы можете сделать ваши аннотации @ExceptionHandler
более конкретными, чтобы они не задерживали это исключение, или вы можете создать конкретный @ExceptionHandler(AccessDeniedException.class)
и просто перестроить исключение в нем.