在spring-security-core jar中,有一个接口UserDetailsService,它有一个方法
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
您可以实现此接口并创建自己的逻辑代码,例如
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
User user = userService.findUserByUsername(username);
if (user != null) {
String password = user.getPassword();
boolean enabled = user.getActive();
boolean accountNonExpired = user.getActive();
boolean credentialsNonExpired = user.getActive();
boolean accountNonLocked = user.getActive();
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role r : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(r.getAuthority()));
}
org.springframework.security.core.userdetails.User securedUser = new org.springframework.security.core.userdetails.User(
username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
return securedUser;
} else {
throw new UsernameNotFoundException(
"Unable to find user with username provided!!");
}
}
然后使用创建 DaoAuthenticationProvider 的对象
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService"></property>
</bean>
最后,将此 DaoAuthenticationProvider 提供给 ProviderManager
<bean class="org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<list>
<ref bean="daoAuthenticationProvider" />
</list>
</constructor-arg>
</bean>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="userDetailsService">
<security:password-encoder hash="plaintext"></security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
添加网页.xml详细信息
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config/spring-*.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>