文章目錄
- 一、@Secured
- 二、@PreAuthority
- 三、@PostAuthorize
接上文
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";
}
}
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5iM1IDM3UWN3AjY0YTYkdzYyYzXwATOxUTM4AzLcdDMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
該角色沒有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";
}
}