7

データベース内のユーザーを Spring Security ユーザーにマップしようとしていますが、うまくいきません。私の UserServiceImpl は次のとおりです(オートワイヤリングは、サーブレットを介して呼び出すと通常は正常に機能しますが、Spring Security で使用すると null ポインターがスローされます...

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService, UserDetailsService {

    protected static Logger logger = Logger.getLogger("service");

    @Autowired
    private UserDAO userDao;

    public UserServiceImpl() {
    }

    @Transactional
    public User getById(Long id) {
        return userDao.getById(id);
    }

    @Transactional
    public User getByUsername(String username) {
        return userDao.getByUsername(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        UserDetails user = null;
        try {
            System.out.println(username);
            User dbUser = getByUsername(username);

            user = new org.springframework.security.core.userdetails.User(
                    dbUser.getUsername(), dbUser.getPassword(), true, true,
                    true, true, getAuthorities(dbUser.getAccess()));
        } catch (Exception e) {
            e.printStackTrace();
            logger.log(Level.FINE, "Error in retrieving user");
            throw new UsernameNotFoundException("Error in retrieving user");
        }

        // Return user to Spring for processing.
        // Take note we're not the one evaluating whether this user is
        // authenticated or valid
        // We just merely retrieve a user that matches the specified username
        return user;
    }

    public Collection<GrantedAuthority> getAuthorities(Integer access) {
        // Create a list of grants for this user
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

        // All users are granted with ROLE_USER access
        // Therefore this user gets a ROLE_USER by default
        logger.log(Level.INFO, "User role selected");
        authList.add(new GrantedAuthorityImpl("ROLE_USER"));

        // Check if this user has admin access
        // We interpret Integer(1) as an admin user
        if (access.compareTo(1) == 0) {
            // User has admin access
            logger.log(Level.INFO, "Admin role selected");
            authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
        }

        // Return list of granted authorities
        return authList;
    }
}

次の例外が発生します (最初の行は System.out です)

dusername
java.lang.NullPointerException
    at org.assessme.com.service.UserServiceImpl.getByUsername(UserServiceImpl.java:40)
    at org.assessme.com.service.UserServiceImpl.loadUserByUsername(UserServiceImpl.java:50)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:81)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:194)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:722)

したがって、userDao が正しく自動配線されていないように見えますが、サーブレットからサービス レイヤーを呼び出すと正常に動作しますが、Spring-Security を使用しているときは明らかにそうではありません。

行 40 は return userDao.getByUsername(username); を参照しています。

@autowired を介して userDao を設定する方法を知っている人はいますか? 私が言うように、サーブレットを介して呼び出すと正常に機能しますが、Spring-Security を使用しようとする場合はそうではありません。

Spring-security でユーザーとパスワードをマップする簡単な方法はありますか?

私の security-app-context は次のとおりです...

<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"
    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"
                    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx">
<context:annotation-config />
<context:component-scan base-package="org.assessme.com." />


    <http pattern="/static/**" security="none" />
    <http use-expressions="true">
        <intercept-url pattern="/login" access="permitAll" />
        <intercept-url pattern="/*" access="isAuthenticated()" />
        <!-- <intercept-url pattern="/secure/extreme/**" access="hasRole('supervisor')" 
            /> -->
        <!-- <intercept-url pattern="/listAccounts.html" access="isAuthenticated()" 
            /> -->
        <!-- <intercept-url pattern="/post.html" access="hasAnyRole('supervisor','teller')" 
            /> -->
<!--        <intercept-url pattern="/*" access="denyAll" /> -->
        <form-login />
        <logout invalidate-session="true" logout-success-url="/"
            logout-url="/logout" />
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="UserDetailsService">
          <password-encoder ref="passwordEncoder"/>
        </authentication-provider>
</authentication-manager>
<context:component-scan base-package="org.assessme.com" /><context:annotation-config />
<beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

<beans:bean class="org.assessme.com.service.UserServiceImpl" id="UserDetailsService" autowire="byType"/>


</beans:beans> 

私の質問は、私の userDao @Autowired が spring-security で動作しないのはなぜだと思いますが、サーブレットで使用してユーザーオブジェクトを返すと正常に動作しますか? たとえば、次のサーブレットは正常に動作します...

オートワイヤリング (NPE をスローするため) がスプリング セキュリティを通過しているときに機能しないのに、サーブレットから呼び出されたときに正常に機能するのはなぜですか?

編集: - 追加

しかし今、私は得る

ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 9 in XML document from ServletContext resource [/WEB-INF/spring/security-app-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 30; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'context:annotation-config'.
4

4 に答える 4

8

Bean 宣言を使用してサービスを作成する必要があります。

<beans:bean class="org.assessme.com.service.UserServiceImpl" id="UserDetailsService"/>

したがって、プロパティを設定して、自動配線の対象として構成する必要がありますautowire。デフォルトはNoです。構成は次のようになります。

<beans:bean class="org.assessme.com.service.UserServiceImpl" id="UserDetailsService"  autowire="byType" />

さらに、プロパティー autowire-candidate="true" を構成することにより、この Bean が他の Bean オートワイヤー プロセスに参加することを示すことができます。

ドキュメントを確認して、Bean のプロパティを自動配線するのに最適な戦略を見つけてください。私は個人的に と を使用byTypeconstructorていますが、実際には要件によって異なります。

別の解決策は、コンテキストdefault-autowire="true"のタグで構成することです。beans

于 2012-07-07T12:39:50.323 に答える
2

私はあなたがちょうどあなたの春のセキュリティの文脈を逃した<context:annotation-config/>と思います。<context:component-scan base-package="..."/>

于 2012-07-07T12:49:14.823 に答える
0

xml ファイルでタグが 2 重になっていることに気付きました。

<context:component-scan base-package="org.assessme.com" /><context:annotation-config />

削除してみましょう。

于 2012-07-09T05:30:24.327 に答える
0

security-app-context を次のように置き換えるだけです。

<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"
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"
                xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx">

<context:annotation-config>
<context:component-scan base-package="org.assessme.com." />

<http pattern="/static/**" security="none" />
<http use-expressions="true">
    <intercept-url pattern="/login" access="permitAll" />
    <intercept-url pattern="/*" access="isAuthenticated()" />
    <!-- <intercept-url pattern="/secure/extreme/**" access="hasRole('supervisor')" 
        /> -->
    <!-- <intercept-url pattern="/listAccounts.html" access="isAuthenticated()" 
        /> -->
    <!-- <intercept-url pattern="/post.html"     access="hasAnyRole('supervisor','teller')" 
        /> -->
<!--        <intercept-url pattern="/*" access="denyAll" /> -->
    <form-login />
    <logout invalidate-session="true" logout-success-url="/"
        logout-url="/logout" />
</http>
<authentication-manager>
    <authentication-provider user-service-ref="UserDetailsService">
      <password-encoder ref="passwordEncoder"/>
    </authentication-provider>
</authentication-manager>
<context:annotation-config />


入力したいくつかの部分を見逃しており、私が修正しました。

于 2012-07-09T07:38:10.150 に答える