springboot现实按列权限查询表
时间: 2023-07-28 10:24:02 浏览: 52
Spring Boot 中实现按列权限查询表的方式可以使用 Spring Security 提供的注解 @PreAuthorize 和 @PostAuthorize。
具体实现步骤如下:
1. 首先,定义一个自定义的注解 @ColumnPermission,用于标记哪些方法需要进行按列权限查询表的操作。该注解可以定义列名数组,表示哪些列需要进行权限检查。
```
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ColumnPermission {
String[] columns() default {};
}
```
2. 在需要进行按列权限查询表的方法上标记 @ColumnPermission 注解,同时在方法参数中添加 Authentication 对象,用于获取当前登录用户的权限信息。
```
@ColumnPermission(columns = {"name", "age"})
public List<User> findUsers(String name, int age, Authentication authentication) {
// 按列权限查询用户表
// ...
}
```
3. 在方法实现中,使用 @PostAuthorize 注解对查询结果进行过滤,只返回当前用户有权限访问的列。
```
@PostAuthorize("hasPermission(returnObject, 'READ')") // 使用 hasPermission 对查询结果进行过滤
public List<User> findUsers(String name, int age, Authentication authentication) {
// 按列权限查询用户表
// ...
return users;
}
```
4. 在 Spring Security 配置中,定义一个实现了 PermissionEvaluator 接口的 bean,在其中实现对查询结果的权限检查逻辑。
```
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration {
@Autowired
private UserPermissionEvaluator userPermissionEvaluator;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(userPermissionEvaluator); // 注入自定义的权限检查器
return expressionHandler;
}
}
```
```
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
// 根据当前用户的权限信息,检查是否有访问指定列的权限
// ...
return true; // 或者返回 false,表示没有权限
}
@Override
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
throw new UnsupportedOperationException();
}
}
```
通过以上步骤,就可以在 Spring Boot 应用中实现按列权限查询表的功能了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)