Java中的@PreAuthorize注解使用詳解
@PreAuthorize注解使用
@PreAuthorize注解會在方法執(zhí)行前進行權(quán)限驗證,支持Spring EL表達式,它是基于方法注解的權(quán)限解決方案。只有當@EnableGlobalMethodSecurity(prePostEnabled=true)的時候,@PreAuthorize才可以使用,@EnableGlobalMethodSecurity注解在SPRING安全中心進行設(shè)置,如下:
/**
* SPRING安全中心
* @author ROCKY
*/
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
}注解如何使用?
@Operation(summary = "通過id查詢檔案報表", description = "通過id查詢檔案報表")
@GetMapping("/{reportId}" )
@PreAuthorize("@pms.hasPermission('archsys_sysarchreport_view')" )
public R getById(@PathVariable("reportId" ) Long reportId) {
return R.ok(sysArchReportService.getById(reportId));
}自定義權(quán)限實現(xiàn)
@PreAuthorize("@pms.hasPermission('archsys_sysarchreport_view')" )
- pms是一個注冊在 Spring容器中的Bean,對應(yīng)的類是cn.hadoopx.framework.web.service.PermissionService;
- hasPermission是PermissionService類中定義的方法;
- 當Spring EL 表達式返回TRUE,則權(quán)限校驗通過;
- PermissionService.java的定義如下:
public class PermissionService {
/**
* 判斷接口是否有任意xxx,xxx權(quán)限
* @param permissions 權(quán)限
* @return {boolean}
*/
public boolean hasPermission(String... permissions) {
if (ArrayUtil.isEmpty(permissions)) {
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(permissions, x));
}
}@RequiredArgsConstructor
@EnableConfigurationProperties(PermitAllUrlProperties.class)
public class PigResourceServerAutoConfiguration {
/**
* 鑒權(quán)具體的實現(xiàn)邏輯
* @return (#pms.xxx)
*/
@Bean("pms")
public PermissionService permissionService() {
return new PermissionService();
}
}到此這篇關(guān)于Java中的@PreAuthorize注解使用詳解的文章就介紹到這了,更多相關(guān)@PreAuthorize注解使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot使用war包部署到外部tomcat過程解析
這篇文章主要介紹了springboot使用war包部署到外部tomcat過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01
SpringMVC實現(xiàn)防止重復(fù)提交表單的方法詳解
在Web開發(fā)中,防止表單重復(fù)提交是一個常見的需求,本文將介紹幾種在SpringMVC框架中防止表單重復(fù)提交的有效方法,有需要的小伙伴可以了解下2025-06-06
深入了解Springboot核心知識點之數(shù)據(jù)訪問配置
這篇文章主要為大家介紹了Springboot核心知識點中的數(shù)據(jù)訪問配置,文中的示例代碼講解詳細,對我們了解SpringBoot有一定幫助,快跟隨小編一起學(xué)習(xí)一下吧2021-12-12

