Spring Security 认证与授权

「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战」。

一、基于配置的认证与授权

  • 新建controller
  • 在该包下新建三个控制器,AdminController,AppController,UserController
    image-20201015094116252.png
  • 分别创建测试API
1
2
3
4
5
6
7
8
9
10
11
12
java复制代码/**
* 模拟后台相关Api接口
*/
@RequestMapping("/admin/api")
@RestController
public class AdminController {

@RequestMapping(value = "/hi",method = RequestMethod.GET)
public String hi(){
return "hi,admin.";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
java复制代码/**
* 模拟对外公开的Api接口
*/
@RequestMapping("/app/api")
@RestController
public class AppController {

@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hi() {
return "hi,app.";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
java复制代码/**
* 模拟用户相关Api接口
*/
@RequestMapping("/user/api")
@RestController
public class UserController {

@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hi() {
return "hi,user.";
}
}
  • 配置资源授权
  • 配置configure
  • 修改之前的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
java复制代码 @Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/api/**").hasRole("ADMIN")
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
// 指定处理登录请求的路径,修改请求的路径,默认为/login
.loginProcessingUrl("/mylogin")
// 使登录页面不设限访问
.permitAll()
.and()
.csrf().disable();

}
  • antMatchers()一个采用ANT模式的URL匹配器
  • ?表示匹配任意单个字符
  • * 表示匹配0或任意数量字符
  • ** 表示匹配0或更多的目录
  • 重启服务
  • 访问api http://localhost:8080/app/api/hi
  • 访问成功 页面显示 hi,app.
  • 访问api http://localhost:8080/user/api/hi
  • 跳转到登录页面
  • 输入自定义的用户名密码
  • 登录成功,页面却报403错误,表示授权失败
  • 认证已经通过,授权失败

因为我们配置的.antMatchers("/user/api/**").hasRole("USER"),需要用户具有USER角色权限

  • 修改配置文件application.yml
1
2
3
4
5
6
yml复制代码spring:
security:
user:
name: caoshenyang
password: 123456
roles: USER
  • 给用户添加USER权限
  • 重启项目
  • 访问api http://localhost:8080/user/api/hi
  • 登录成功后,页面显示hi,user.

访问api http://localhost:8080/admin/api/hi

出现同样情况

修改配置文件application.yml

给用户添加上ADMIN权限

重启项目

访问正常,页面显示hi,admin.

二、基于内存的多用户设置

1. 实现自定义的UserDetailsService

1
2
3
4
5
6
7
8
9
10
java复制代码@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//MD5 加密 明文 111 加密后 698d51a19d8a121ce581499d7b701668
//noop 明文
manager.createUser(User.withUsername("aa").password("{MD5}698d51a19d8a121ce581499d7b701668").roles("USER").build());
manager.createUser(User.withUsername("bb").password("{noop}222").roles("USER").build());

return manager;
}

注意: SpringSecurity5.x 以上版本需要配置加密否则会出现以下异常

1
java复制代码There is no PasswordEncoder mapped for the id "null"

SpringSecurity5.x 加密方式采用{Id}password的格式配置

我们可以看一下PasswordEncoderFactories自带的加密方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
java复制代码public class PasswordEncoderFactories {
public static PasswordEncoder createDelegatingPasswordEncoder() {
String encodingId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap();
encoders.put(encodingId, new BCryptPasswordEncoder());
encoders.put("ldap", new LdapShaPasswordEncoder());
encoders.put("MD4", new Md4PasswordEncoder());
encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
encoders.put("sha256", new StandardPasswordEncoder());
encoders.put("argon2", new Argon2PasswordEncoder());
return new DelegatingPasswordEncoder(encodingId, encoders);
}

private PasswordEncoderFactories() {
}
}
  • 重新启动
  • 输入账号密码
  • 登录成功
  • 此配置会覆盖原先application.yml中的配置

2. 通过congfigure

1
2
3
4
5
6
7
8
java复制代码@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("tom").password("111").roles("ADMIN","USER")
.and()
.withUser("lisi").password("222").roles("USER");
}

同实现自定义UserDetailsService大同小异,此配置会覆盖原先application.yml中的配置和自定义UserDetailsService中配置,选其中之一就可以

三、 基于默认数据库模型的授权与认证

  • 查看InMemoryUserDetailsManager源码
  • 实现了UserDetailsManager接口

image-20201016101659111.png

  • 选中UserDetailsManager接口,Ctrl+H

发现实现该接口的还有另一个实现类JdbcUserDetailsManager
image-20201016101511396.png

从命名应该能猜到该实现类通过JDBC方式连接数据库

  • 为工程引入JDBCMYSQL依赖
1
2
3
4
5
6
7
8
9
xml复制代码<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
  • application.yml配置数据连接参数
1
2
3
4
5
6
yml复制代码spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/springSecurityDemo?useUnicode=true&&characterEncoding=utf8&&useSSL=false&&serverTimezone=Asia/Shanghai
  • 创建数据库springSecurityDemo

SpringSecurity提供了默认的数据库模型

1
2
3
4
5
java复制代码public JdbcUserDetailsManagerConfigurer<B> withDefaultSchema() {
this.initScripts.add(new ClassPathResource(
"org/springframework/security/core/userdetails/jdbc/users.ddl"));
return this;
}

地址在org/springframework/security/core/userdetails/jdbc/users.ddl

image-20201016105051344.png

1
2
3
mysql复制代码create table users(username varchar_ignorecase(50) not null primary key,password varchar_ignorecase(500) not null,enabled boolean not null);
create table authorities (username varchar_ignorecase(50) not null,authority varchar_ignorecase(50) not null,constraint fk_authorities_users foreign key(username) references users(username));
create unique index ix_auth_username on authorities (username,authority);

注意: MySql不支持varchar_ignorecase这种类型,将其改为varchar

1
2
3
mysql复制代码create table users(username VARCHAR(50) not null primary key,password VARCHAR(500) not null,enabled boolean not null);
create table authorities (username VARCHAR(50) not null,authority VARCHAR(50) not null,constraint fk_authorities_users foreign key(username) references users(username));
create unique index ix_auth_username on authorities (username,authority);
  • 执行建表语句
  • 创建两张表

image-20201016110104571.png

authorities表

image-20201016110547743.png

users表

image-20201016110743875.png

  • 构建JdbcUserDetailsManager实例,让SpringSecurity使用数据库来管理用户,和基于内存类似,只是用户信息来源于数据库
  • 引入DataSource
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
java复制代码@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/api/**").hasRole("ADMIN")
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
// 指定处理登录请求的路径,修改请求的路径,默认为/login
.loginProcessingUrl("/mylogin")
.permitAll()
.and()
.csrf().disable();
}

/**
* 基于默认数据库数据模型用户设置
*/
@Bean
public UserDetailsService userDetailsService(){
JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
manager.setDataSource(dataSource);

//MD5 加密 名文 111 加密后 698d51a19d8a121ce581499d7b701668
manager.createUser(User.withUsername("aa").password("{MD5}698d51a19d8a121ce581499d7b701668").roles("USER").build());
manager.createUser(User.withUsername("bb").password("{noop}222").roles("USER").build());
return manager;
}
}
  • 重启项目
  • 访问api http://localhost:8080/user/api/hi
  • 输入用户名aa 密码111
  • 访问成功

发现数据库存储了这些信息

image-20201016114243117.png

image-20201016114311093.png

并且注意到在我们设置的权限前加了ROLE_前缀

  • 查看JdbcUserDetailsManager源码

发现定义了大量的sql执行语句

createUser()其实就相当与执行下面SQL语句

1
java复制代码insert into users (username, password, enabled) values (?,?,?)

上述代码中存在一个问题,每当我们重启项目时都会去创建用户,但是username是主键,会出现主键冲突异常

1
java复制代码nested exception is java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'aa' for key 'PRIMARY'
  • 稍作修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
java复制代码/**
* 基于默认数据库数据模型用户设置
*/
@Bean
public UserDetailsService userDetailsService() {
JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
manager.setDataSource(dataSource);
if (!manager.userExists("aa")) {
//MD5 加密 名文 111 加密后 698d51a19d8a121ce581499d7b701668
manager.createUser(User.withUsername("aa").password("{MD5}698d51a19d8a121ce581499d7b701668").roles("USER").build());

}
if (!manager.userExists("bb")) {
manager.createUser(User.withUsername("bb").password("{noop}222").roles("USER").build());
}
return manager;
}
  • 重启项目
  • 正常运行
  • 通过修改数据库数据添加管理员用户

image-20201016142700235.png

image-20201016142756146.png

  • 访问api http://localhost:8080/admin/api/hi

输入自己定义的管理员用户名密码,访问成功

四、 基于自定义数据库模型的授权与认证

在项目开发中,默认的数据库模型太过于简单,往往不能满足我们业务的需求,SpringSecurity同样支持,自定义数据库模型的授权与认证。

  • 下面接入自定义的数据库模型
  • 持久层框架使用MyBatis-Plus
  • 使用lombok插件简化代码
  • 为工程引入相关依赖
1
2
3
4
5
6
7
8
9
10
xml复制代码<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>

1. 实现UserDetails

之前的案例中通过实现UserDetailsService,并加上注解注入spring容器,Spring Security会自动发现并使用, UserDetailsService也仅仅实现了一个loadUserByUsername()方法,用于获取UserDetails对象 ,UserDetails包含验证所需的一系列信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
java复制代码public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();

String getPassword();

String getUsername();

boolean isAccountNonExpired();

boolean isAccountNonLocked();

boolean isCredentialsNonExpired();

boolean isEnabled();
}

所以无论数据来源是什么,或者数据库结构如何变化,我们只需要构造一个UserDetails即可。

1.1 实现自己的用户表

1
2
3
4
5
6
7
8
mysql复制代码CREATE TABLE `t_user` (
`id` BIGINT ( 20 ) NOT NULL AUTO_INCREMENT,
`username` VARCHAR ( 60 ) NOT NULL,
`password` VARCHAR ( 60 ) NOT NULL,
`enable` TINYINT ( 4 ) NOT NULL DEFAULT '1' COMMENT '用户是否可用',
`roles` text CHARACTER SET utf8mb4 COMMENT '用户角色,多个角色之间用逗号隔开',
PRIMARY KEY ( `id` ), KEY ( `username` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
  • username字段上添加索引,提高搜索速度
  • 手动插入两条数据

image-20201016153806726.png

1.2 编写我们的User实体

  • 创建entity包存放实体
  • 新建User实体类
1
2
3
4
5
6
7
8
java复制代码@Data
public class User {
private Long id;
private String username;
private String password;
private String roles;
private boolean enable;
}
  • 实现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
java复制代码@Data
public class User implements UserDetails {
private Long id;
private String username;
private String password;
private String roles;
private boolean enable;

private List<GrantedAuthority> authorities;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return this.enable;
}
}

重写方法

  • isAccountNonExpired()、isAccountNonLocked()、isCredentialsNonExpired()暂时用不到全部返回true
  • isEnabled()对应enable字段
  • getAuthorities()原本对应的是roles字段,但是自己定义的结构变化,所以我们先新建一个authorities,后期进行填充。

1.3 持久层准备

  • 创建mapper
  • 创建UserMapper
1
2
3
4
5
6
java复制代码@Component
public interface UserMapper extends BaseMapper<User> {

@Select("SELECT * FROM t_user WHERE username = #{username}")
User findByUserName(@Param("username") String username);
}
  • 启动类添加包扫描注解
1
2
3
4
5
6
7
8
java复制代码@SpringBootApplication
@MapperScan("com.yang.springsecurity.mapper")
public class SpringSecurityApplication {

public static void main(String[] args) {
SpringApplication.run(SpringSecurityApplication.class, args);
}
}
  • 编写业务代码
  • 创建service
  • 创建MyUserDetailsService实现UserDetailsService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
java复制代码@Service
public class MyUserDetailsService implements UserDetailsService {

@Autowired
private UserMapper userMapper;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//查询用户信息
User user = userMapper.selectByUsername(username);
if (user==null){
throw new UsernameNotFoundException(username+"用户不存在");
}
//重新填充roles
user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
return user;
}
}

注意: SpringSecurity5.x 以上版本需要配置加密否则会出现以下异常

1
java复制代码There is no PasswordEncoder mapped for the id "null"
  • 配置默认加密方式
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
java复制代码@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource dataSource;
@Autowired
private MyUserDetailsService myUserDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/api/**").hasRole("ADMIN")
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
// 指定处理登录请求的路径,修改请求的路径,默认为/login
.loginProcessingUrl("/mylogin")
.permitAll()
.and()
.csrf().disable();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
}

}
  • 重启项目
  • 访问api http://localhost:8080/admin/api/hi
  • 输入用户名密码
  • 访问成功

到此我们已经实现了自定义的数据库模型的授权与认证,后期可以根据项目需要丰富验证逻辑,加强安全性

这里一直有个问题,为什么我们的数据库里权限需要加上ROLE_前缀?

查看 hasRole() 方法源码就很容易理解了

1
2
3
4
5
6
7
8
9
java复制代码private static String hasRole(String role) {
Assert.notNull(role, "role cannot be null");
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException(
"role should not start with 'ROLE_' since it is automatically inserted. Got '"
+ role + "'");
}
return "hasRole('ROLE_" + role + "')";
}

如果不想要匹配这个前缀可换成**hasAuthority()**方法

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%