spring-security关于hasRole的坑及解决
作者:fhzmWJ
spring-security关于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,不应该用ROLE_开头因为会自动加一个。
hasRole在进行权限判断时会被追加前缀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()
;
}还是应该直接相信报错提示的,,,,,,走了太多弯路。
springboot整合spring-security注意事项,不要踩坑
1.Spring Boot与Maven
Spring Boot提供了一个spring-boot-starter-security启动程序,它将Spring Security相关的依赖项聚合在一起。
利用启动器的最简单和首选方法是使用IDE集成(Eclipse,IntelliJ,NetBeans)或通过https://start.spring.io使用Spring Initializr。
加入的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>2.授权
我们的示例仅要求用户进行身份验证,并且已针对应用程序中的每个URL进行了身份验证。
我们可以通过向http.authorizeRequests()方法添加多个子项来指定网址的自定义要求。
例如:下面展示一些 内联代码片。
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”角色的用户。您会注意到,由于我们正在调用hasRole方法,因此我们不需要指定“ROLE_”前缀。
- 4.任何以“/ db /”开头的URL都要求用户同时拥有“ROLE_ADMIN”和“ROLE_DBA”。您会注意到,由于我们使用的是hasRole表达式,因此我们不需要指定“ROLE_”前缀。
3.认证
到目前为止,我们只看了最基本的身份验证配置。
我们来看一些稍微更高级的配置身份验证选项。
3.1内存中认证
我们已经看到了为单个用户配置内存中身份验证的示例。
以下是配置多个用户的示例:下面展示一些 内联代码片。
@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的身份验证的更新。以下示例假定您已在应用程序中定义了DataSource。
该JDBC-javaconfig样品提供了使用基于JDBC认证的一个完整的示例。
下面展示一些 `内联代码片`。
@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"));
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
