Security注解:@PreAuthorize,@PostAuthorize, @Secured, EL實現方法安全


說明

(1)JDK版本:1.8

(2)Spring Boot 2.0.6

(3)Spring Security 5.0.9

(4)Spring Data JPA 2.0.11.RELEASE

(5)hibernate5.2.17.Final

(6)MySQLDriver 5.1.47

(7)MySQL 8.0.12

 

需求緣起

       在之前的章節中我們介紹過通過注解的方式進行權限的控制了,這里再詳細的講解下方法級安全的幾個注解。

一、注解式方法級安全開啟

       需要在WebSecuirtyConfig添加配置:

@Configuration
@EnableWebSecurity //啟用Spring Security.

////會攔截注解了@PreAuthrize注解的配置.
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

}

 

 

二、允許的注解

       這里主要@PreAuthorize, @PostAuthorize, @Secured這三個注解可以使用。

2.1 @Secured

       當@EnableGlobalMethodSecurity(securedEnabled=true)的時候,@Secured可以使用:

 

@GetMapping("/helloUser")
@Secured({"ROLE_normal","ROLE_admin"})
public String helloUser() {
    return "hello,user";
}

說明:擁有normal或者admin角色的用戶都可以方法helloUser()方法。另外需要注意的是這里匹配的字符串需要添加前綴“ROLE_“

 

       如果我們要求,只有同時擁有admin & noremal的用戶才能方法helloUser()方法,這時候@Secured就無能為力了。

 

2.2 @PreAuthorize

       Spring的 @PreAuthorize/@PostAuthorize 注解更適合方法級的安全,也支持Spring 表達式語言,提供了基於表達式的訪問控制。

       當@EnableGlobalMethodSecurity(prePostEnabled=true)的時候,@PreAuthorize可以使用:

 

@GetMapping("/helloUser")
@PreAuthorize("hasAnyRole('normal','admin')")
public String helloUser() {
    return "hello,user";
}

 

說明:擁有normal或者admin角色的用戶都可以方法helloUser()方法。

       此時如果我們要求用戶必須同時擁有normal和admin的話,那么可以這么編碼:

 

@GetMapping("/helloUser")
@PreAuthorize("hasRole('normal') AND hasRole('admin')") 
public String helloUser() {
    return "hello,user";
}

 

       此時如果使用user/123登錄的話,就無法訪問helloUser()的方法了。

 

2.3 @PostAuthorize

       @PostAuthorize 注解使用並不多,在方法執行后再進行權限驗證,適合驗證帶有返回值的權限,Spring EL 提供 返回對象能夠在表達式語言中獲取返回的對象returnObject。

當@EnableGlobalMethodSecurity(prePostEnabled=true)的時候,@PostAuthorize可以使用:

@GetMapping("/helloUser")
@PostAuthorize(" returnObject!=null &&  returnObject.username == authentication.name")
public User helloUser() {
        Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user;
        if("anonymousUser".equals(pricipal)) {
            user = null;
        }else {
            user = (User) pricipal;
        }
        return user;
}

 

       這三個最常用也就是@PreAuthorize這個注解了,在使用中主要是配合Spring EL表達式。


免責聲明!

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



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