03.基于Method安全表达式

基于Method安全表达式

针对方法级别的访问控制比较复杂, spring security 提供了4种注解分别是
@PreAuthorize , @PostAuthorize ,@PreFilter , @PostFilter。
1)开启方法级别的注解配置
在security配置类中添加注解

1
2
3
4
5
6
/**
* Security配置类
*/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启注解支持
public class SecurityConfiguration extends WebSecurityConfigurerAdapter

在方法上使用注解
@PreAuthorize :

注解适合进入方法前的权限验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 查询所有用户
*
* @return
*/
@RequestMapping("/findAll")
@PreAuthorize("hasRole('ADMIN')")//需要ADMIN权限
public String findAll(Model model) {
    List<User> userList = userService.list();
    model.addAttribute("userList", userList);
    return "user_list";
}
 
/**
* 用户修改页面跳转
*
* @return
*/
@RequestMapping("/update/{id}")
@PreAuthorize("#id<10")//针对参数权限限定 id<10可以访问
public String update(@PathVariable Integer id, Model model) {
    User user = userService.getById(id);
    model.addAttribute("user", user);
    return "user_update";
}

@PostAuthorize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * 根据用户ID查询用户
 *
 * @return
 */
@GetMapping("/{id}")
@ResponseBody
@PostAuthorize("returnObject.username==authentication.principal.username")//returnObject返回参数 只能查询自己的信息
public User getById(@PathVariable Integer id) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    //如果返回true,代表这个登录认证的信息来源于自动登录
    if(RememberMeAuthenticationToken.class.isAssignableFrom(authentication.getClass())){
        throw new RememberMeAuthenticationException("认证来源于remember me");
    }
    User user = userService.getById(id);
    return user;
}

@PreFilter

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 用户删除-多选删除
 *
 * @return
 */
@GetMapping("/delByIds")
@PreFilter(filterTarget = "ids",value = "filterObject%2==0")//剔除参数为基数的值 只保留偶数
public String delByIds(@RequestParam(value = "id") List<Integer> ids) {
    for (Integer id : ids) {
        System.out.println(id);
    }
    return "redirect:/user/findAll";
}

http://localhost:8080/user/delByIds?id=5&id=16

@PostFilter

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * 查询所有用户-返回json数据
 *
 * @return
 */
@RequestMapping("/findAllTOJson")
@ResponseBody
@PostFilter("filterObject.id%2==0")//只返回偶数集合
public List<User> findAllTOJson() {
    List<User> userList = userService.list();
    return userList;
}

http://localhost:8080/user/findAllTOJson

 

posted @   __破  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示