天天看點

springboot+springsecurity+mybatis plus注解實作對方法的權限處理

文章目錄

  • ​​一、@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";
    }
}      
springboot+springsecurity+mybatis plus注解實作對方法的權限處理

該角色沒有ROLE_user或者ROLE_admin權限,是以無法通路該方法

springboot+springsecurity+mybatis plus注解實作對方法的權限處理
springboot+springsecurity+mybatis plus注解實作對方法的權限處理

二、@PreAuthority

實作該注解需要在類上加入

@EnableGlobalMethodSecurity( prePostEnabled = true)
@RestController
@RequestMapping("/test")
@EnableGlobalMethodSecurity( prePostEnabled = true)
public class SecurityController {

    @GetMapping("/add")
    @PreAuthorize("hasAuthority('admin')")
    public String add() {
        return "add";
    }

}      
springboot+springsecurity+mybatis plus注解實作對方法的權限處理

由于有該admin權限,是以可以猜到結果為add

springboot+springsecurity+mybatis plus注解實作對方法的權限處理
springboot+springsecurity+mybatis plus注解實作對方法的權限處理

三、@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";
    }
}      
springboot+springsecurity+mybatis plus注解實作對方法的權限處理

繼續閱讀