2013-02-20 69 views
1

我從動彈簧瞭解春季安全,我想實現這樣的:我有一個Web應用程序中,有兩種存儲在數據庫中的用戶:如何與彈簧安全認證規則數據庫用戶

1)管理員

2)客戶

這是彈簧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" 
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.0.3.xsd"> 

<http auto-config="true"> 
    <intercept-url pattern="/welcome*" access="ROLE_USER" /> 
</http> 

<authentication-manager> 
    <authentication-provider> 
    <user-service> 
    <user name="name" password="password" authorities="ROLE_USER" /> 
    </user-service> 
    </authentication-provider> 
</authentication-manager> 

</beans:beans> 

因此,如何聯繫:

<user-service> <user name="name" password="password" authorities="ROLE_USER" /> </user-service> 給數據庫用戶條目(管理員和客戶端)? 我將此部分添加到web.xml中:

<!-- Spring Security --> 
<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> 

回答

2

您不能這樣映射。

您需要爲此使用自定義UserDetailsService。使用userDetailsS​​ervice,您可以從數據庫加載用戶並將其傳遞給spring安全框架。

public class UserDetailsServiceImpl implements UserDetailsService { 
    public UserDetails loadUserByUsername(String userName) 
      throws UsernameNotFoundException, DataAccessException { 
     User user = getUser(userName); //Load user from database 
     if (user == null) { 
      throw new UsernameNotFoundException("User not found: " + userName); 
     } 
     return user; 
    } 
} 

的security.xml

<authentication-manager> 
    <authentication-provider user-service-ref="userDetailsService" /> 
</authentication-manager>