让Spring Security适应系统,而非让系统适应Spring Security,是Spring Security框架开发者和使用者的共识。
下面我们将使用自定义数据库模型接入Spring Security,数据库依然是MySQL,持久层框架则选用MyBatis(倾向于使用JPA的读者也可以自行选型,它们在Spring Security部分的实践是一样的)。旁枝末节的知识会点到即止,我们重点介绍Spring Security相关的内容,所以期望读者自行阅读相关资料,也可以选择暂时略过
在前面的博客中,我们使用了 InMemoryUserDetailsManager 和 JdbcUserDetailsManager 两个UserDetailsService 实现类。生效方式也很简单,只需加入 Spring 的 IoC 容器,就会被 Spring Security自动发现并使用。自定义数据库结构实际上也仅需实现一个自定义的UserDetailsService。
UserDetailsService仅定义了一个loadUserByUsername方法,用于获取一个UserDetails对象。UserDetails对象包含了一系列在验证时会用到的信息,包括用户名、密码、权限以及其他信息,Spring Security会根据这些信息判定验证是否成功。
/**
* Provides core user information.
*
* <p>
* Implementations are not used directly by Spring Security for security purposes. They
* simply store user information which is later encapsulated into {@link Authentication}
* objects. This allows non-security related user information (such as email addresses,
* telephone numbers etc) to be stored in a convenient location.
* <p>
* Concrete implementations must take particular care to ensure the non-null contract
* detailed for each method is enforced. See
* {@link org.springframework.security.core.userdetails.User} for a reference
* implementation (which you might like to extend or use in your code).
*
* @see UserDetailsService
* @see UserCache
*
* @author Ben Alex
*/
public interface UserDetails extends Serializable {
// ~ Methods
// =================================================================================&