spring-security關(guān)于hasRole的坑及解決
spring-security關(guān)于hasRole的坑
.access(“hasRole(‘ROLE_USER’)”) 如果用
.hasRole(“ROLE_USER”) 會報錯。。。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘springSecurityFilterChain’ defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method ‘springSecurityFilterChain’ threw exception; nested exception is java.lang.IllegalArgumentException: role should not start with ‘ROLE_’ since it is automatically inserted. Got ‘ROLE_USER’
像下面代碼這樣是可以的,不要ROLE_USER,直接USER,不應(yīng)該用ROLE_開頭因為會自動加一個。
hasRole在進行權(quán)限判斷時會被追加前綴ROLE_。
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/design", "/orders") .hasRole("USER") .antMatchers("/", "/**").access("permitAll") .and() .formLogin() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .and() .csrf() .ignoringAntMatchers("/h2-console/**") .and() .headers() .frameOptions() .sameOrigin() ; }
或者這樣也是可以的:
import org.springframework.security.config.annotation.web .builders.HttpSecurity; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/design", "/orders") .access("hasRole('ROLE_USER')") .antMatchers("/", "/**").access("permitAll") .and() .formLogin() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .and() .csrf() .ignoringAntMatchers("/h2-console/**") .and() .headers() .frameOptions() .sameOrigin() ; }
還是應(yīng)該直接相信報錯提示的,,,,,,走了太多彎路。
springboot整合spring-security注意事項,不要踩坑
1.Spring Boot與Maven
Spring Boot提供了一個spring-boot-starter-security啟動程序,它將Spring Security相關(guān)的依賴項聚合在一起。
利用啟動器的最簡單和首選方法是使用IDE集成(Eclipse,IntelliJ,NetBeans)或通過https://start.spring.io使用Spring Initializr。
加入的依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2.授權(quán)
我們的示例僅要求用戶進行身份驗證,并且已針對應(yīng)用程序中的每個URL進行了身份驗證。
我們可以通過向http.authorizeRequests()方法添加多個子項來指定網(wǎng)址的自定義要求。
例如:下面展示一些 內(nèi)聯(lián)代碼片。
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/resources/**", "/signup", "/about").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .anyRequest().authenticated() .and() // ... .formLogin(); }
- 1.http.authorizeRequests()方法有多個子項,每個匹配器按其聲明的順序進行考慮。
- 2.我們指定了任何用戶都可以訪問的多種URL模式。具體來說,如果URL以“/ resources /”開頭,等于“/ signup”或等于“/ about”,則任何用戶都可以訪問請求。
- 3.任何以“/ admin /”開頭的URL都將僅限于具有“ROLE_ADMIN”角色的用戶。您會注意到,由于我們正在調(diào)用hasRole方法,因此我們不需要指定“ROLE_”前綴。
- 4.任何以“/ db /”開頭的URL都要求用戶同時擁有“ROLE_ADMIN”和“ROLE_DBA”。您會注意到,由于我們使用的是hasRole表達式,因此我們不需要指定“ROLE_”前綴。
3.認證
到目前為止,我們只看了最基本的身份驗證配置。
我們來看一些稍微更高級的配置身份驗證選項。
3.1內(nèi)存中認證
我們已經(jīng)看到了為單個用戶配置內(nèi)存中身份驗證的示例。
以下是配置多個用戶的示例:下面展示一些 內(nèi)聯(lián)代碼片。
@Bean public UserDetailsService userDetailsService() throws Exception { // ensure the passwords are encoded properly UserBuilder users = User.withDefaultPasswordEncoder(); InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); manager.createUser(users.username(“user”).password(“password”).roles(“USER”).build()); manager.createUser(users.username(“admin”).password(“password”).roles(“USER”,“ADMIN”).build()); return manager; }
3.2 JDBC身份驗證
您可以找到支持基于JDBC的身份驗證的更新。以下示例假定您已在應(yīng)用程序中定義了DataSource。
該JDBC-javaconfig樣品提供了使用基于JDBC認證的一個完整的示例。
下面展示一些 `內(nèi)聯(lián)代碼片`。
@Autowired private DataSource dataSource; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // ensure the passwords are encoded properly UserBuilder users = User.withDefaultPasswordEncoder(); auth .jdbcAuthentication() .dataSource(dataSource) .withDefaultSchema() .withUser(users.username("user").password("password").roles("USER")) .withUser(users.username("admin").password("password").roles("USER","ADMIN")); }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot整合Java?DL4J實現(xiàn)交通標(biāo)志識別系統(tǒng)全過程
在自動駕駛系統(tǒng)中,交通標(biāo)志識別是實現(xiàn)車輛智能化的關(guān)鍵技術(shù)之一,本文介紹了利用SpringBoot和JavaDeeplearning4j構(gòu)建交通標(biāo)志識別系統(tǒng)的方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-10-10MyBatis?Mapper.XML?標(biāo)簽使用小結(jié)
在MyBatis中,通過resultMap可以解決字段名和屬性名不一致的問題,對于復(fù)雜的查詢,引用實體或使用<sql>標(biāo)簽可以定義復(fù)用的SQL片段,提高代碼的可讀性和編碼效率,使用這些高級映射和動態(tài)SQL技巧,可以有效地處理復(fù)雜的數(shù)據(jù)庫交互場景2024-10-10Spring Cloud 的 Hystrix.功能及實踐詳解
這篇文章主要介紹了Spring Cloud 的 Hystrix.功能及實踐詳解,Hystrix 具備服務(wù)降級、服務(wù)熔斷、線程和信號隔離、請求緩存、請求合并以及服務(wù)監(jiān)控等強大功能,需要的朋友可以參考下2019-07-07springboot項目打成jar包后無法獲取static下的靜態(tài)資源文件的問題分析
這篇文章主要介紹了springboot項目打成jar包后無法獲取static下的靜態(tài)資源文件的問題分析,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08