Spring Security: SecurityContextHolder.getContext().getAuthentication() возвращает null на странице калитки

Я использую Spring MVC (для REST), Spring Security 3 и Apache Wicket (UI) в Google App Engine. Все работает нормально, за исключением того, что у меня возникли проблемы с прохождением аутентификации на странице калитки через SecurityContextHolder после входа в систему.

Я искал эту проблему в Google, но, похоже, ни один из них не работает для меня. Я подозреваю, что это что-то не так с моим веб-xml. Кто-нибудь может помочь. Спасибо.

Я использую учебные пособия по Spring Security в Google App Engine из http://blog.springsource.org/2010/08/02/spring-security-in-google-app-engine/

Вот мой web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app>        
 <display-name>MTP Portal</display-name>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/mtp-web-servlet.xml, /WEB-INF/mtp-web-security-context.xml
    </param-value>
</context-param>

<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>
</filter-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>mtp-web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>mtp-web</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>WicketApp</filter-name>
    <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
    <init-param>
        <param-name>applicationFactoryClassName</param-name>
        <param-value>org.apache.wicket.spring.SpringWebApplicationFactory</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>WicketApp</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Here is my spring security config:

<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
     xmlns:b="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<global-method-security pre-post-annotations="enabled"/>

<http pattern="/images/**" security="none"/>
<http pattern="/css/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/api/**" security="none"/>
<http pattern="/favicon.ico" security="none"/>
<http pattern="/disabled" security="none"/>

<http use-expressions="true" entry-point-ref="gaeEntryPoint" auto-config="true">
    <intercept-url pattern="/" access="permitAll"/>
    <intercept-url pattern="/api/**" access="permitAll"/>
    <intercept-url pattern="/admin/logout" access="permitAll"/>
    <intercept-url pattern="/register" access="hasRole('NEW_USER')"/>
    <intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/>
    <custom-filter position="PRE_AUTH_FILTER" ref="gaeFilter"/>
</http>

<b:bean id="gaeEntryPoint"
        class="com.peerbuccoss.apps.mtp.web.authentication.impl.GoogleAccountsAuthenticationEntryPoint"/>

<b:bean id="gaeFilter" class="com.peerbuccoss.apps.mtp.web.authentication.filter.GaeAuthenticationFilter">
    <b:property name="authenticationManager" ref="authenticationManager"/>
    <b:property name="failureHandler">
        <b:bean class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
            <b:property name="exceptionMappings">
                <b:map>
                    <b:entry key="org.springframework.security.authentication.DisabledException"
                             value="/disabled"/>
                </b:map>
            </b:property>
        </b:bean>
    </b:property>
</b:bean>

<authentication-manager alias="authenticationManager">
    <authentication-provider ref="gaeAuthenticationProvider"/>
</authentication-manager>

<b:bean id="gaeAuthenticationProvider"
        class="com.peerbuccoss.apps.mtp.web.authentication.provider.GoogleAccountsAuthenticationProvider"/>


person shameem_z    schedule 01.07.2012    source источник
comment
Я могу получить объект аутентификации из контекста безопасности, если я изменю URL-адрес перехвата с ‹pattern-url-intercept=/ access=permitAll/› на ‹pattern-url-intercept=/ * доступ=разрешитьВсе/›   -  person shameem_z    schedule 02.07.2012


Ответы (1)


Я не уверен, какой URL-адрес не может получить SecurityContext (возможно, вы можете предоставить пример URL-адреса), но SecurityContext не будет заполнен для любого URL-адреса, сопоставленного с security="none". Это связано с тем, что security="none" указывает Spring Security полностью игнорировать этот URL-адрес. Если вам нужно получить доступ к SecurityContext по URL-адресу, разрешенному для каждого пользователя, вам нужно использовать PermitAll.

PS: Если это не поможет, вы можете предоставить пример URL-адреса, по которому у вас возникли проблемы с аутентификацией. Вы также можете предоставить подробную информацию о том, что вы подразумеваете под «проблемами с получением аутентификации на странице калитки» (т. е. является ли она нулевой, выдает исключение и т. д.).

person Rob Winch    schedule 01.07.2012
comment
Спасибо за ваш ответ. В основном я пытаюсь получить доступ к странице администратора по следующему URL-адресу localhost:8080/admin, который перенаправляет меня на страницу Google страница авторизации. После успешного входа в систему с использованием учетной записи электронной почты (@peerbuccoss.com), если электронная почта не найдена, я бы перенаправил на страницу регистрации, чтобы предложить пользователю ввести свою личную информацию для завершения процесса регистрации, в противном случае следует перенаправить на страницу администратора. . Вход в систему выполнен успешно, но я получаю нулевое значение при вызове SecurityContextHolder.getContext().getAuthentication() на странице регистрации. localhost:8080/register. - person shameem_z; 01.07.2012
comment
Я добавил новую роль, чтобы моя страница перенаправляла на страницу регистрации. ‹intercept-url pattern=/register access=hasRole('NEW_USER')/›. Здесь вы можете получить пример кода, на который я ссылаюсь (github.com/ SpringSource/spring-security/tree/master/samples/gae). Но он использует Spring MVC + Security и GAE. Для весенней калитки у меня есть дополнительные фильтры. - person shameem_z; 01.07.2012
comment
У меня та же проблема, и мой register.htm(jsp) выдает ошибку 403. Как вы решили эту проблему, потому что у моего аутентифицированного пользователя есть права доступа = {NEW_USER} - person Axwack; 11.06.2015