1.设计数据表
创建用户表,角色表和用户角色关联表,为了方便测试,首先在数据库中预先存放几条数据。
2.创建项目,依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.13</version>
</dependency>
3.配置数据库
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
4.创建实体类
分别创建角色表和用户表两个实体类,代码如下:
public class Role {
private Integer id;
private String name;
private String nameZh;
//省略getter/setter
}
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
private List<Role> roles;
/**
* 获取当前用户对象所具有的角色信息
* @return
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role:roles) {
authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
}
return authorities;
}
@Override
public String getPassword() { //获取当前用户对象的密码
return password;
}
@Override
public String getUsername() { //获取当前用户对象的用户名
return username;
}
@Override
public boolean isAccountNonExpired() { //当前账户是否未过期
return true;
}
@Override
public boolean isAccountNonLocked() { //当前账户是否未锁定
return !locked;
}
@Override
public boolean isCredentialsNonExpired() { //当前账户密码是否未过期
return true;
}
@Override
public boolean isEnabled() { //当前账户是否可用
return enabled;
}
//省略getter/setter
}
用户需要实现UserDetails接口,并实现该接口中的7个方法,如上…用户根据实际情况设置这7个方法的返回值。默认情况下不需要开发者自己进行密码角色信息的对比,开发者只需要提供相关的信息即可,例如getPassword()方法返回的密码和用户登录输入的密码不匹配,会自动抛出BadCredentialsException异常。
1.5创建userService
@Service
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUserName(username);
if (null==user){
throw new UsernameNotFoundException("账户不存在");
}
user.setRoles(userMapper.getUserRolesByUid(user.getId()));
return user;
}
}
定义一个UserService实现UserDetailsService接口,并实现该接口中的loadUserByUsername(String username)方法,该方法的参数就是用户登录时输入的用户名,通过用户名去数据库查找用户,如果没有查找到用户,就抛出账户不存在的异常。如果查找到了用户,就继续查找该用户拥有的角色信息,并将获取的user对象返回,再由系统提供的DaoAuthenticationProvider类去对比密码是否正确
注:loadUserByUsername(String username) 在用户登录时自动调用。
这里涉及到的UserMapper和UserMapper.xml代码如下:
@Mapper
public interface UserMapper {
User loadUserByUserName(String username);
List<Role> getUserRolesByUid(Integer id);
}
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="edu.wl.springbootsecurity2.mapper.UserMapper">
<select id="loadUserByUserName" resultType="edu.wl.springbootsecurity2.bean.User">
select * from user where username=#{username}
</select>
<select id="getUserRolesByUid" resultType="edu.wl.springbootsecurity2.bean.Role">
select * from role r,user_role ur where r.id=ur.rid and ur.uid=#{id}
</select>
</mapper>
1.6 配置Spring Security
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* 将userService配置到AuthenticationManagerBuilder
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
}
这里将不在配置内存用户,而是将刚刚创建的userService配置到AuthenticationManagerBuilder中。