服务器之家

服务器之家 > 正文

Spring Security基于数据库实现认证过程解析

时间:2020-08-17 12:14     来源/作者:柒丶月

创建数据库

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
SET FOREIGN_KEY_CHECKS=0;
    -- ----------------------------
    -- Table structure for role
    -- ----------------------------
    DROP TABLE IF EXISTS `role`;
    CREATE TABLE `role` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(32) DEFAULT NULL,
    `nameZh` varchar(32) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    -- ----------------------------
    -- Records of role
    -- ----------------------------
    INSERT INTO `role` VALUES ('1', 'dba', '数据库管理员');
    INSERT INTO `role` VALUES ('2', 'admin', '系统管理员');
    INSERT INTO `role` VALUES ('3', 'user', '用户');
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(32) DEFAULT NULL,
    `password` varchar(255) DEFAULT NULL,
    `enabled` tinyint(1) DEFAULT NULL,
    `locked` tinyint(1) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES ('1', 'root', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
    INSERT INTO `user` VALUES ('2', 'admin', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
    INSERT INTO `user` VALUES ('3', 'sang', '$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq', '1', '0');
    -- ----------------------------
    -- Table structure for user_role
    -- ----------------------------
    DROP TABLE IF EXISTS `user_role`;
    CREATE TABLE `user_role` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `uid` int(11) DEFAULT NULL,
    `rid` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    -- ----------------------------
    -- Records of user_role
    -- ----------------------------
    INSERT INTO `user_role` VALUES ('1', '1', '1');
    INSERT INTO `user_role` VALUES ('2', '1', '2');
    INSERT INTO `user_role` VALUES ('3', '2', '2');
    INSERT INTO `user_role` VALUES ('4', '3', '3');
    SET FOREIGN_KEY_CHECKS=1;

导入依赖

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<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>5.1.46</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid-spring-boot-starter</artifactId>
  <version>1.1.22</version>
</dependency>

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/javaboy?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

让bean实现UserDetails接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class User implements UserDetails {
  private Integer id;
  private String username;
  private String password;
  private Boolean enabled;
  private Boolean locked;
 
  private List<Role> roles;
 
  public List<Role> getRoles() {
    return roles;
  }
 
  public void setRoles(List<Role> roles) {
    this.roles = roles;
  }
 
  public Integer getId() {
    return id;
  }
 
  public void setId(Integer id) {
    this.id = id;
  }
 
  public void setUsername(String username) {
    this.username = username;
  }
 
  public void setPassword(String password) { this.password = password; }
 
  public void setEnabled(Boolean enabled) {
    this.enabled = enabled;
  }
 
  public void setLocked(Boolean locked) {
    this.locked = locked;
  }
 
  @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;
  }
 
  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;
  }
}

?
1
2
3
4
5
6
public class Role {
  private Integer id;
  private String name;
  private String nameZh;
...
}

userMapper

在类上直接加@Mapper或者在SpringBoot启动类上配置全局的扫描@MapperScan(basePackages="")

?
1
2
3
4
5
6
@Mapper
public interface UserMapper {
  User loadUserByUsername(String username);
 
  List<Role> getUserRolesById(Integer id);
}

?
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qwl.mysecuritydb.mapper.UserMapper">
  <select id="loadUserByUsername" resultType="com.qwl.mysecuritydb.bean.User">
    select * from user where username = #{username}
  </select>
  <select id="getUserRolesById" resultType="com.qwl.mysecuritydb.bean.Role">
    select * from role where id in(select rid from user_role where uid=#{id})
  </select>
</mapper>

userService 同样也要继承UserServiceDetails接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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.getUserRolesById(user.getId()));
    return user;
  }
}

HelloController

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RestController
public class HelloController {
  @GetMapping("/hello")
  public String hello(){
    return "hello security";
  }
 
  @GetMapping("/dba/hello")
  public String dba(){
    return "hello dba";
  }
 
  @GetMapping("/admin/hello")
  public String admin(){
    return "hello admin";
  }
 
  @GetMapping("/user/hello")
  public String user(){
    return "hello user";
  }
}

SecurityConfig

  • SercurityConfig需要继承WebSecurityConfigurerAdapter类,并在类上加@Configuration
  • SpringSecurity5.0之后密码必须加密
  • 把数据库查出的用户信息交给SpringSecurity处理
  • 配置httpSercurity
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  UserService userService;
 
        //把数据库查出的用户信息交给SpringSecurity处理
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService);
  }
 
  @Bean
  PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
  }
 
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/dba/**").hasRole("dba")
        .antMatchers("/admin/**").hasRole("admin")
        .antMatchers("/user/**").hasRole("user")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .permitAll()
        .and()
        .csrf().disable();
 
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/qiuwenli/p/13445594.html

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
返回顶部