Соответствующий подстановочный знак является строгим, но объявление не может быть найдено для элемента ‘bean’

#java #spring #spring-security #cas

#java #весна #spring-безопасность #cas

Вопрос:

Я пытаюсь интегрировать проект Spring Security с сервером CAS для аутентификации путем настройки клиента CAS. Прежде чем применить его к моему веб-приложению, я попробовал его в примере проекта Spring Security.

Я добавил плагины CAS, как указано здесь https://wiki.jasig.org/display/CASC/Configuring the JA-SIG CAS Client for Java using Spring адаптируя его к конкретному случаю.

Когда я запускаю или отлаживаю образец веб-приложения, я получаю ошибку, о которой я упоминал в заголовке, который ссылается на строку

  <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
  

из следующего spring-security.xml:

  <beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
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.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

    <!-- access denied page -->
    <access-denied-handler error-page="/403" />
    <form-login 
        login-page="/login" 
        default-target-url="/welcome" 
        authentication-failure-url="/login?error" 
        username-parameter="username"
        password-parameter="password" />
    <logout logout-success-url="/login?logout"  />
    <!-- enable csrf protection -->
    <csrf/>
</http>

<!-- Select users and user_roles from database -->
<authentication-manager>
    <authentication-provider>
        <jdbc-user-service id="userService" data-source-ref="dataSource"
            users-by-username-query=
                "select username,password, enabled from users where username=?"
            authorities-by-username-query=
                "select username, role from user_roles where username =?  " />
    </authentication-provider>
</authentication-manager>

    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
    <security:filter-chain-map path-type="ant">
        <security:filter-chain pattern="/" filters="casValidationFilter, wrappingFilter" />
        <security:filter-chain pattern="/secure/receptor" filters="casValidationFilter" />
        <security:filter-chain pattern="/j_spring_security_logout" filters="logoutFilter,etf,fsi" />
        <security:filter-chain pattern="/**" filters="casAuthenticationFilter, casValidationFilter, wrappingFilter, sif,j2eePreAuthFilter,logoutFilter,etf,fsi"/>
    </security:filter-chain-map>
</bean>
<bean id="sif" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>
<bean id="preAuthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
    <property name="preAuthenticatedUserDetailsService">
        <bean id="userDetailsServiceWrapper" class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper">
            <property name="userDetailsService" ref="userService"/>
        </bean>
    </property>
</bean>

<bean id="preAuthEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />

<bean id="j2eePreAuthFilter" class="org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthenticatedProcessingFilter">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="authenticationDetailsSource">
        <bean class="org.springframework.security.web.authentication.WebAuthenticationDetailsSource" />
    </property>
</bean>

<bean id="logoutFilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">
    <constructor-arg value="/"/>
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/>
        </list>
    </constructor-arg>
</bean>

<bean id="servletContext" class="org.springframework.web.context.support.ServletContextFactoryBean"/>

<bean id="etf" class="org.springframework.security.web.access.ExceptionTranslationFilter">
    <property name="authenticationEntryPoint" ref="preAuthEntryPoint"/>
</bean>

<bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
    <property name="allowIfAllAbstainDecisions" value="false"/>
    <property name="decisionVoters">
        <list>
            <ref bean="roleVoter"/>
        </list>
    </property>
</bean>
<bean id="fsi" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager"/>
    <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
    <property name="securityMetadataSource">
        <security:filter-invocation-definition-source>
            <security:intercept-url pattern="/**" access="ROLE_ANONYMOUS,ROLE_USER"/>
        </security:filter-invocation-definition-source>
    </property>
</bean>
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>

<bean id="securityContextHolderAwareRequestFilter" class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter"/>
<bean class="org.jasig.cas.client.validation.Saml11TicketValidator" id="ticketValidator">
    <constructor-arg index="0" value={cas.login} />

    <!--<property name="proxyGrantingTicketStorage" ref="proxyGrantingTicketStorage" />-->
    <!--<property name="proxyCallbackUrl" value="http://localhost:8080/ui/" />-->
</bean>
<bean id="proxyGrantingTicketStorage" class="org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl" />
<bean id="casAuthenticationFilter" class="org.jasig.cas.client.authentication.AuthenticationFilter">
    <property name="casServerLoginUrl" value={cas.login.url} />
    <property name="serverName" value={cas.login.url} />
</bean>
<bean id="casValidationFilter" class="org.jasig.cas.client.validation.Saml11TicketValidationFilter">
    <property name="serverName" value="http://localhost:8080/ui" />
    <property name="exceptionOnValidationFailure" value="true" />
    <!--<property name="proxyGrantingTicketStorage" ref="proxyGrantingTicketStorage" />-->
    <property name="redirectAfterValidation" value="true" />
    <property name="ticketValidator" ref="ticketValidator" />
    <!--<property name="proxyReceptorUrl" value="/secure/receptor" />-->
</bean>
<bean id="wrappingFilter" class="org.jasig.cas.client.util.HttpServletRequestWrapperFilter" />

</beans:beans>
  

Любая помощь приветствуется.

Комментарии:

1. Вы в основном скопировали все и ожидаете, что это сработает. У вас нет security префикса, поскольку вы сделали его своим корнем. Поэтому удалите security: префиксы и добавьте префикс ко всем вашим объявлениям bean beans: . Кроме того, вы также дублируете свою конфигурацию и переопределяете множество уже зарегистрированных компонентов, я настоятельно рекомендую вам сначала попытаться понять, что нужно, и изменить старый (устаревший?) пример вашего фактического кода.

2. Я бы также настоятельно рекомендовал прочитать раздел 6.3 справочного руководства. Что довольно четко объясняет, как настроить клиент с помощью Spring Security.

3. Большое вам спасибо за предложения. Однако мне пока не удалось заставить его работать. Какие компоненты я переопределил? Вы правы в отношении префикса безопасности, который я не включил в xmlns: security =» springframework.org/schema/security »

Ответ №1:

Вам также необходимо добавить XSD в расположение схемы.

 xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd"