public class WebSecurityConfigurer {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers("/index").permitAll()
.anyRequest().authenticated();
return http.build();
}
}
出现错误
java: 无法将类 org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry中的方法 requestMatchers应用到给定类型;
需要: org.springframework.security.web.util.matcher.RequestMatcher[]
找到: java.lang.String
原因: varargs 不匹配; java.lang.String无法转换为org.springframework.security.web.util.matcher.RequestMatcher
请问该如何解决
根据您提供的代码和错误信息,问题出现在 requestMatchers 方法的参数类型不匹配上。requestMatchers 方法期望的是 org.springframework.security.web.util.matcher.RequestMatcher[] 类型的参数,但您传入的是 java.lang.String 类型的参数。
要解决这个问题,您可以将 requestMatchers 方法的参数修改为 org.springframework.security.web.util.matcher.RequestMatcher[] 类型的数组,并将需要配置的路径包装成 RequestMatcher 对象。例如,将 .requestMatchers("/index").permitAll() 修改为 .requestMatchers(new AntPathRequestMatcher("/index")).permitAll()。这样可以将字符串路径 "/index" 封装成一个 RequestMatcher 对象,使其与方法的参数类型匹配。
下面是修复后的代码示例:
public class WebSecurityConfigurer {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers(new AntPathRequestMatcher("/index")).permitAll()
.anyRequest().authenticated();
return http.build();
}
}
请注意,AntPathRequestMatcher 是 Spring Security 提供的一种常用的路径匹配器,用于对 URL 路径进行模式匹配。您可以根据实际需求选择不同的 RequestMatcher 实现类,例如 AntPathRequestMatcher、RegexRequestMatcher 等,以满足您的安全配置需求。
根据错误提示信息,该问题出现在 http.authorizeHttpRequests().requestMatchers("/index").permitAll()
这行代码中。从错误信息中可以看出,requestMatchers()
方法需要传入 RequestMatcher[]
类型的参数,但是实际传入的却是 String
类型的参数。
解决方法是将参数由 String
类型改为 AntPathRequestMatcher
类型,将其存放在数组中,然后传入 requestMatchers()
方法:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(new AntPathRequestMatcher("/index")).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
}
在上述示例代码中,使用 AntPathRequestMatcher
类型的实例,使用 new
关键字创建对象,并将其存放在数组中传入了 requestMatchers()
方法中。该方法能够正确的将参数解析为 RequestMatcher
数组,达到授权匹配的目的。