在 Ruoyi 中进行权限控制,主要涉及到以下几个步骤:
定义角色和权限:
role_permission
)来表示。用户与角色的关联:
user_role
)来表示。权限点的定义:
permissionId
)。角色与权限点的关联:
role_permission_point
)来表示。实现权限控制逻辑:
配置权限规则:
application.yml
或 application.properties
)中配置权限规则。下面是一个简单的示例代码,展示如何在 Ruoyi 中进行权限控制:
假设你已经定义了 role
、permission
、user
、user_role
、role_permission
和 role_permission_point
数据表。
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
@Entity
public class Permission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// getters and setters
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
// getters and setters
}
@Entity
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
// getters and setters
}
@Entity
public class RolePermission {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
@ManyToOne
@JoinColumn(name = "permission_id")
private Permission permission;
// getters and setters
}
@Entity
public class RolePermissionPoint {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
@ManyToOne
@JoinColumn(name = "permission_point_id")
private PermissionPoint permissionPoint;
// getters and setters
}
在服务层中实现权限检查逻辑:
@Service
public class PermissionService {
@Autowired
private UserRoleRepository userRoleRepository;
@Autowired
private RolePermissionRepository rolePermissionRepository;
public boolean hasPermission(Long userId, Long permissionId) {
// 获取用户角色
UserRole userRole = userRoleRepository.findByUserId(userId);
if (userRole == null) {
return false;
}
// 获取角色权限点
List<RolePermissionPoint> rolePermissionPoints = rolePermissionRepository.findByRoleId(userRole.getRole().getId());
// 检查权限点是否包含目标权限
for (RolePermissionPoint point : rolePermissionPoints) {
if (point.getPermissionPoint().getId().equals(permissionId)) {
return true;
}
}
return false;
}
}
在控制器中使用 @RequiresPermissions
注解进行权限检查:
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
private PermissionService permissionService;
@GetMapping("/data")
@RequiresPermissions("data:view")
public ResponseEntity<String> getData() {
return ResponseEntity.ok("Data");
}
}
在 application.yml
中配置权限规则:
ruoyi:
security:
permissions:
data: view, add, edit, delete
通过以上步骤,你可以在 Ruoyi 中实现基本的权限控制功能。根据具体需求,你可以进一步扩展和优化权限控制逻辑。