如何基于SpringSecurity的@PreAuthorize實現(xiàn)自定義權(quán)限校驗方法
一、前言
在我們一般的web系統(tǒng)中必不可少的就是權(quán)限的配置,也有經(jīng)典的RBAC權(quán)限模型,是基于角色的權(quán)限控制。這是目前最常被開發(fā)者使用也是相對易用、通用權(quán)限模型。當(dāng)然SpringSecurity
已經(jīng)實現(xiàn)了權(quán)限的校驗,但是不夠靈活,我們可以自己寫一下校驗條件,從而更加的靈活!
很多開源框架中也是用的比較多,小編看了一下若依是自己寫了一個注解實現(xiàn)的,pig是使用@PreAuthorize
來實現(xiàn)自己的校驗方式,小編以pig框架的為例。
二、SpringSecurity的@PreAuthorize
@PreAuthorize("hasAuthority('system:dept:list')") @GetMapping("/hello") public String hello (){ return "hello"; }
我們進(jìn)去源碼方法中看看具體實現(xiàn),我們進(jìn)行模仿!
// 調(diào)用的方法 @Override public final boolean hasAuthority(String authority) { return hasAnyAuthority(authority); } @Override public final boolean hasAnyAuthority(String... authorities) { return hasAnyAuthorityName(null, authorities); } private boolean hasAnyAuthorityName(String prefix, String... roles) { Set<String> roleSet = getAuthoritySet(); // 便利規(guī)則,看看是否有權(quán)限 for (String role : roles) { String defaultedRole = getRoleWithDefaultPrefix(prefix, role); if (roleSet.contains(defaultedRole)) { return true; } } return false; }
三、權(quán)限校驗判斷工具
@Component("pms") public class PermissionService { /** * 判斷接口是否有xxx:xxx權(quán)限 * @param permission 權(quán)限 * @return {boolean} */ public boolean hasPermission(String permission) { if (StrUtil.isBlank(permission)) { return false; } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { return false; } Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); return authorities.stream().map(GrantedAuthority::getAuthority).filter(StringUtils::hasText) .anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x)); } }
四、controller使用
@GetMapping("/page" ) @PreAuthorize("@pms.hasPermission('order_get')" ) public R getOrderInPage(Page page, OrderInRequest request) { return R.ok(orderInService.queryPage(page, request)); }
參數(shù)說明:
主要是采用SpEL表達(dá)式語法,
@pms
:是一個我們自己配置的spring容器起的別名,能夠正確的找到這個容器類;
hasPermission('order_get')
:容器內(nèi)方法名稱和參數(shù)
五、總結(jié)
這樣就完成了自定義校驗,具體的校驗可以自己在配置里進(jìn)行修改,當(dāng)然也可以自己寫一個注解來進(jìn)行自定義校驗,可以參考若依的注解!
到此這篇關(guān)于如何基于SpringSecurity的@PreAuthorize實現(xiàn)自定義權(quán)限校驗方法的文章就介紹到這了,更多相關(guān)SpringSecurity自定義權(quán)限校驗方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java.lang.Runtime.exec() Payload知識點(diǎn)詳解
在本篇文章里小編給大家整理的是一篇關(guān)于java.lang.Runtime.exec() Payload知識點(diǎn)相關(guān)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2020-03-03解決idea2020 maven無法自動導(dǎo)包的問題
這篇文章主要介紹了解決idea2020 maven無法自動導(dǎo)包的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02Spring Boot學(xué)習(xí)入門之AOP處理請求詳解
AOP為Aspect Oriented Programming的縮寫,意為:面向切面編程,通過預(yù)編譯方式和運(yùn)行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護(hù)的一種技術(shù),下面這篇文章主要給大家介紹了關(guān)于Spring Boot學(xué)習(xí)入門之AOP處理請求的相關(guān)資料,需要的朋友可以參考下。2017-09-09