Spring Security默認是禁用注解的,要想開啟注解,要在繼承WebSecurityConfigurerAdapter
的類加@
EnableGlobalMethodSecurity注解,並在該類中將AuthenticationManager
定義為Bean
@Configuration @EnableWebSecurity // 啟用Spring Security的Web安全支持 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true) //開啟方法權限注解支持 public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * Spring Security默認是禁用注解的,要想開啟注解,要在繼承WebSecurityConfigurerAdapter的類加@EnableGlobalMethodSecurity注解, * 並在該類中將AuthenticationManager定義為Bean。 * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }
@EnableGlobalMethodSecurity
分別有prePostEnabled
、securedEnabled
、jsr250Enabled
三個字段,其中每個字段代碼一種注解支持,默認為false,true為開啟
1.JSR-250注解
導入坐標
<!--JSR250:security權限注解--> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency>
在指定方法中使用方法注解@RolesAllowed,@DenyAll,@PermitAll
@DenyAll 和 @PermitAll 代表全部拒絕和全部通過 @RolesAllowed({"USER", "ADMIN"}) 代表標注的方法只要具有USER, ADMIN任意一種權限就可以訪問。這里可以省略前綴ROLE_,實際的權限可能是ROLE_ADMIN。
2.securedEnabled注解
@Secured("ROLE_ADMIN")
@Secured({ "ROLE_DBA", "ROLE_ADMIN" })
3.prePostEnabled注解(支持表達式)
主要注解
@PreAuthorize --適合進入方法之前驗證授權
@PostAuthorize --檢查授權方法之后才被執行
@PostFilter --在方法執行之后執行,而且這里可以調用方法的返回值,然后對返回值進行過濾或處理或修改並返回
@PreFilter --在方法執行之前執行,而且這里可以調用方法的參數,然后對參數值進行過濾或處理或修改
@PreAuthorize("authentication.principal.username == 'tom' ")
@PreAuthorize("hasRole('ROLE_ADMIN')")
另外該注解還支持自定義匹配器,詳細配置可見鏈接:https://blog.csdn.net/qq_32867467/article/details/95078794