ingframework.security.userdetails.UserDetails#isCredentialsNonExpired()
*/
public boolean isCredentialsNonExpired() {
return true;
}
/* (non-Javadoc)
* @see org.springframework.security.userdetails.UserDetails#isEnabled()
*/
public boolean isEnabled() {
return !this.disabled;
}
// setters and getters
}
Spring Security 2配置精讲 上(10)
时间:2011-10-16
实现UserDetails接口中的每个函数,其实没什么很大的难度,除了其中的一个函数我需要额外强调一下:
Java代码
/* (non-Javadoc)
* @see org.springframework.security.userdetails.UserDetails#getAuthorities()
*/
public GrantedAuthority[] getAuthorities() {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
for(Role role : roles) {
grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
}
return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);
}
/* (non-Javadoc)
* @see org.springframework.security.userdetails.UserDetails#getAuthorities()
*/
public GrantedAuthority[] getAuthorities() {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
for(Role role : roles) {
grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
}
return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);
}
这个函数的实际作用是根据User返回这个User所拥有的权限列表。如果以上面曾经用过的例子来说,如果当前User是downpour,我需要得到ROLE_USER和ROLE_ADMIN;如果当前User是robbin,我需要得到ROLE_USER。
了解了含义,实现就变得简单了,由于User与Role是多对多的关系,我们可以通过User得到所有这个User所对应的Role,并把这些Role的name拼装起来返回。
由此可见,实现UserDetails接口,并没有什么神秘的地方,它只是实际上在一定程度上只是代替了使用配置文件的硬编码:
Xml代码
<user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="downpour" password="downpour" authorities="ROLE_USER, ROLE_ADMIN" />
3. 实现UserDetailsService接口
Java代码
@Repository("securityManager")
public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService {
/**
* Init sessionFactory here because the annotation of Spring 2.5 can not support override inject
*
* @param sessionFactory
*/
@Autowired
public void init(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);
if(users.isEmpty()) {
throw new UsernameNotFoundException("User &quo
|