简介:

  上篇文章向读者介绍的认证数据都是定义在内存中的,在真实项目中,用户的基本信息以及角色等都存储在数据库中,因此需要从数据库中获取数据进行认证。

开始:

首先建表并且插入数据:

pom.xml

   <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>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

创建实体类:

public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean locked;
private List<Role> roles;
  
//获取当前用户对象所具有的所有角色信息
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(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 }
public class Role {
private Integer id;
private String name;
private String nameZh;
//省略getter/setter }

Service:

  定义UserService实现UserDetailsService接口,并实现该接口中的loadUserByUsemame方法,该方法的参数就是用户登录时输入的用户名,通过用户名去数据库中查找用户,如果没有查找到用户,就抛出一个账户不存在的异常,如果查找到了用户,就继续查找该用户所具有的角色信息,并将获取到的user对象返回,再由系统提供DaoAuthenticationProvider 类去比对密码是否正确。

@Service
public class UserService implements UserDetailsService {
@Autowired
UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.loadUserByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("账户不存在!");
}
user.setRoles(userMapper.getUserRolesByUid(user.getId()));
return user;
}
}

Mapper:

@Mapper
public interface UserMapper {
User loadUserByUsername(String username);
List<Role> getUserRolesByUid(Integer id);
}
<mapper namespace="org.sang.security02.mapper.UserMapper">
<select id="loadUserByUsername" resultType="org.sang.security02.model.User">
select * from user where username=#{username}
</select>
<select id="getUserRolesByUid" resultType="org.sang.security02.model.Role">
select * from role r,user_role ur where r.id=ur.rid and ur.uid=#{id}
</select>
</mapper>

配置SpringSecurity

角色继承:

 在上面定义了三种角色,但是这三种角色之间不具备任何关系,一般来说角色之间是有关系的,例如ROLE admin -般既具有admin的权限,又具有user的权限。那么如何配置

这种角色继承关系呢?在Spring Security 中只需要开发者提供一-个RoleHierarchy即可。

  以上面的案例为例,假设ROLE_dba是终极大Boss,具有所有的权限,ROLE_admin具有ROLE _user 的权限,ROL_user 则是一个公共角色,即ROLE_admin继承ROLE_user、 ROLE_dba继承ROLE_ admin, 要描述这种继承关系,只需要开发者在Spring Security 的配置类中提供一个RoleHierarchy即可,代码如下:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Bean
RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
String hierarchy = "ROLE_dba > ROLE_admin ROLE_admin > ROLE_user";
roleHierarchy.setHierarchy(hierarchy);
return roleHierarchy;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);      //没有将用户存在内存中,而是从数据库中取出来
} @Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O object) {
object.setSecurityMetadataSource(cfisms());
object.setAccessDecisionManager(cadm());
return object;
}
})
.and()
.formLogin()
.loginProcessingUrl("/login").permitAll()
.and()
.csrf().disable();
}
@Bean
CustomFilterInvocationSecurityMetadataSource cfisms() {
return new CustomFilterInvocationSecurityMetadataSource();
}
@Bean
CustomAccessDecisionManager cadm() {
return new CustomAccessDecisionManager();
}
}

Controller:

@RestController
public class HelloController {
@GetMapping("/admin/hello")
public String admin() {
return "hello admin";
}
@GetMapping("/db/hello")
public String dba() {
return "hello dba";
}
@GetMapping("/user/hello")
public String user() {
return "hello user";
}
}

最新文章

  1. eventbus 备注
  2. 用户IP地址的三个属性的区别(HTTP_X_FORWARDED_FOR,HTTP_VIA,REM_addr
  3. PostgreSQL模仿Oracle的instr函数
  4. &lt;转载&gt; OpenGL Projection Matrix
  5. FTS抓包看蓝牙的SDP整个过程
  6. 用xshell操作linux系统的常用命令
  7. Apache的httpd命令详解
  8. wchar_t是内置还是别名(亲测有效:wchar_t在windows下是16位整数的别名,在linux等平台下是32位整数的别名。MSVC2008开始默认是/Zc:wchar_t)
  9. sar使用说明
  10. Shell命令-文件及内容处理之split、paste
  11. HTML5 使用 JS 生成二维码,带头像
  12. Perl分片技术
  13. 关于 Nginx 配置 WebSocket 400 问题
  14. Yarn 入门
  15. linux编程之信号量
  16. NodeServices
  17. r test
  18. 树莓派进阶之路 (015) - 树莓派使用DS18B20模块测量温度
  19. Thread.currentThread()与this的区别
  20. linux传输文件命令: rz 和 sz

热门文章

  1. org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3报错解决
  2. java集合与数组之间转换
  3. 使用Azure CLI创建Linux虚拟机
  4. selenium,测试套件的使用
  5. CSS-14-浮动
  6. Kotlin DSL for HTML实例解析
  7. 【存储类、链接、存储管理】分配内存:malloc()、free()
  8. angular之模块开发一
  9. Python报错:PermissionError: [Errno 13] Permission denied
  10. javase第一章(了解java)