Spring Security 框架应用
基于 t_account(用户表)和 t_role(角色)表实现自定义用户认证和授权,一个用户只能拥有一个角色
t_account 和 t_role 表结果如下所示,在 t_role 表中有三个角色,分别是管理员、店主和消费者:
1. 使用 Spring Initializr 新建一个 Spring Boot 框架项目,项目名自定义
框架中需要集成 Web 开发,并且修改 Spring boot 版本为 2.6.7。
2. 在项目中引入 Spring Security 依赖“spring-boot-starter-security”。
<!--开启安全机制-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.使用 UserDetailsService 身份认证方式实现用户登录和授权
基于 t_account(用户表)和 t_role(角色)两张表
实体类继承Security 框架中的User
public class TAccountUser extends User {
public TAccountUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
private int accountId;
private String roleName;
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getRoleName() {