2 Spring Security实战
在这一节我们讲演示一个基于用户、角色、权限的更为实用的例子;一个用户有一个或多个角色,每个角色有一个或多个的权限。
新建应用,信息如下:
Group:top.wisely
Artifact:learning-spring-security-in-battle
Dependencies:Spring Security、Spring Web Starter、Spring Data JPA、MySQL Driver、Lombok
build.gradle文件中的依赖如下:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
//...
}
删除上一个应用的数据库SYS_USER表,在application.yml中连接数据库:
spring:
datasource:
url: jdbc:mysql://localhost:3306/first_db?useSSL=false
username: root
password: zzzzzz
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
用户、角色、权限的实体分别是SysUser、SysRole、SysAuthority:
我们也看权限的实体:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class SysAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name; //权限名称
private String value; //权限值
public SysAuthority(String name, String value) {
this.name = name;
this.value = value;
}
}
角色的实体:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class SysRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany(targetEntity = SysAuthority.class)
private Set<SysAuthority> authorities; // 角色和权限是多对多的关系
public SysRole(String name, Set<SysAuthority> authorities) {
this.name = name;
this.authorities = authorities;
}
}
用户的实体:
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class SysUser implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTI

该博客详细介绍了如何在Spring Boot 2.x中实现一个基于用户、角色和权限的完整Spring Security实战示例。内容包括应用创建、依赖设置、数据库配置、实体类定义、权限控制以及初始化数据。此外,还提到了新书《从企业级开发到云原生微服务:Spring Boot 实战》的相关信息。
最低0.47元/天 解锁文章
482

被折叠的 条评论
为什么被折叠?



