.authorizeRequests()
/\*普通用户访问的url\*/
.antMatchers("/user/\*\*").hasRole("USER")
/\*管理员用户访问的url\*/
.antMatchers("/admin/\*\*").hasRole("ADMIN")
.anyRequest().authenticated() //其他多有路径都必须认证
.and()
.formLogin()
.loginProcessingUrl("/login")
.permitAll() //访问“/login”接口不需要进行身份认证了,防止重定向死循环
.and()
.csrf().disable(); //关闭csrf
}
}
然后就可以发现,若要访问admin/hello,用户名和密码必须是admin才可以
若使用aoxiu这种用户的身份就会报错
### 三、基于数据库的认证
#### 1、SpringSecurity基于数据库认证
1. 创建项目,添加如下依赖

lombok用于使用注解替代getter、setter等方法

2. 在application.yml文件中配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
logging:
level:
com.example.bdatabaserole.mapper: debug #打印SQL语句
mybatis:
mapper-locations: classpath:mappers/*.xml
type-aliases-package: com.example.securitydatebase.mapper
server:
port: 8082
3. 创建实体类
UserInfo
package com.beixi.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Data //lombok注解省略get/set等方法
public class UserInfo implements Serializable,UserDetails {
private int id;
private String username;
private String password;
private List<Role> roleList;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
for (Role r