文章目录
接上文
springboot+springsecurity+mybatis plus之用户授权
一、@Secured
需要在类上开启该注解 @EnableGlobalMethodSecurity(securedEnabled = true)
@RestController
@RequestMapping("/test")
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityController {
@GetMapping("/add")
@Secured({"ROLE_user","ROLE_admin"})
public String add() {
return "add merchandise";
}
}
该角色没有ROLE_user或者ROLE_admin权限,所以无法访问该方法
二、@PreAuthority
实现该注解需要在类上加入
@EnableGlobalMethodSecurity( prePostEnabled = true)
@RestController
@RequestMapping("/test")
@EnableGlobalMethodSecurity( prePostEnabled = true)
public class SecurityController {
@GetMapping("/add")
@PreAuthorize("hasAuthority('admin')")
public String add() {
return "add";
}
}
由于有该admin权限,所以可以猜到结果为add
三、@PostAuthorize
同样需要在类上加入
@EnableGlobalMethodSecurity(prePostEnabled = true)
这个注解会在方法执行之后进行权限判断
@RestController
@RequestMapping("/test")
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityController {
@GetMapping("/update")
@PostAuthorize("hasAnyAuthority('user')")
public String update() {
System.out.println("update方法已经执行!");
return "update";
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步