spring security 注解@EnableGlobalMethodSecurity詳解


 1、Spring Security默認是禁用注解的,要想開啟注解,需要在繼承WebSecurityConfigurerAdapter的類上加@EnableGlobalMethodSecurity注解,來判斷用戶對某個控制層的方法是否具有訪問權限

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
...........................
}

2、例如下面代碼就表示如果用戶具有admin角色,就能訪問listAllUsers方法,但是如果方法前不加@preAuthorize注解,意味着所有用戶都能訪問listAllUsers

方法

    @PreAuthorize("hasRole('admin')")
    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    @ResponseBody
    public List<User> listAllUsers() {
        List<User> users = userService.findAll();
        if(users.isEmpty()){
            return null;
        }
        return users;
    }
  

3、@EnableGlobalMethodSecurity詳解

3.1、@EnableGlobalMethodSecurity(securedEnabled=true)
         開啟@Secured 注解過濾權限

3.2、@EnableGlobalMethodSecurity(jsr250Enabled=true)

          開啟@RolesAllowed 注解過濾權限 

3.3、@EnableGlobalMethodSecurity(prePostEnabled=true)
         使用表達式時間方法級別的安全性 4個注解可用

  • @PreAuthorize 在方法調用之前,基於表達式的計算結果來限制對方法的訪問
  • @PostAuthorize 允許方法調用,但是如果表達式計算結果為false,將拋出一個安全性異常
  • @PostFilter 允許方法調用,但必須按照表達式來過濾方法的結果
  • @PreFilter 允許方法調用,但必須在進入方法之前過濾輸入值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM