其实我想自定义spring security的登录页面。 我收到错误:
requestMatchers cannot be resolved
。import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.requestMatchers("/home/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
return http.build();
}
}
您的代码中存在语法问题。 requestMatchers 方法需要在 http 对象上调用,而不是直接在 http.requestMatchers 上调用。
这是您的 SecurityConfig 类的更正版本:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws
Exception {
http
.authorizeRequests(requests -> requests
.antMatchers("/home/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(login -> login
.loginPage("/login")
.permitAll()
)
.logout(logout -> logout
.permitAll()
);
return http.build();
}
}
在此更正后的版本中,authorizeRequests 用于配置基于 URL 的授权,antMatchers 用于指定无需身份验证即可允许的 URL 模式(“/home/**”)。
此外,formLogin方法用于配置登录表单设置,包括自定义登录页面(“/login”)并允许所有用户访问它。
确保导入必要的类:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
通过这些更正,您的 Spring Security 配置应该按预期工作。