我可以通過XML文件和一些Java代碼來解釋你。以下是我如何登錄並分配角色。您還可以查詢數據庫中的角色。
安全的applicationContext.xml:
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider user-service-ref="LoginServiceImpl">
<security:password-encoder ref="encoder"/>
</security:authentication-provider>
</security:authentication-manager>
<beans:bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="LoginServiceImpl"/>
<beans:property name="passwordEncoder" ref="encoder"/>
</beans:bean>
以上是我的數據庫認證碼,其referes到LoginServiceImpl的豆,從那裏我正在尋找在DB用戶。模型類已經實現了UserDetails。
LoginServiceImpl:
@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{
@Autowired private PersonDAO personDAO;
@Autowired private Assembler assembler;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
Person person = personDAO.findPersonByUsername(username.toLowerCase());
if(person == null) { throw new UsernameNotFoundException("Wrong username or password");}
return assembler.buildUserFromUserEntity(person);
}
public LoginServiceImpl() {
}
}
當用戶在數據庫中,我構建可通過彈簧安全的會議,所有使用的對象。這是怎麼一回事呢:
@Service("assembler")
public class Assembler {
@Transactional(readOnly = true)
User buildUserFromUserEntity(Person userEntity){
String username = userEntity.getUsername().toLowerCase();
String password = userEntity.getPassword();
boolean enabled = userEntity.isEnabled();
boolean accountNonExpired = userEntity.isAccountNonExpired();
boolean credentialsNonExpired = userEntity.isCredentialsNonExpired();
boolean accountNonLocked = userEntity.isAccountNonLocked();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(username,password,enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,authorities);
}
}
正如你所看到的,我加入的角色,但我還可以查詢數據庫,或者你發現任何其他邏輯,然後拿過來,用戶將有那個角色。理想情況下,Person模型類應該具有到Role類的一對多映射以及其中的用戶角色。 如果這不是你要找的,我會刪除我的答案,只是讓我知道。