我已经设置了一个带有 JWT 身份验证的自定义 SecurityFilterChain,为了进行测试,我允许测试路由上的所有请求。
即使禁用了 httpBasic 和 formLogin 身份验证,我仍然收到 401 未经授权。 因此,我从 @SpringBootApplication 中排除了 SpringAutoConfiguration 类。然后我收到了 Whitelabel 错误页面。
我是初学者,所以请指导我解决这个问题。
我尝试了 httpSecurity 的许多变体,但找不到解决方案。
@Configuration
@EnableWebSecurity
public class AppConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// simple httpSecurity just to check
// return http.sessionManagement(s ->
// s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .authorizeRequests(auth ->
// auth.requestMatchers("/hello").permitAll()
// .anyRequest().authenticated())
//// .httpBasic(Customizer.withDefaults())
//// .formLogin(FormLoginConfigurer::disable)
// .build();
// original code which I want to work with.
return http
.authorizeHttpRequests(auth -> auth
// .requestMatchers(HttpMethod.GET, "/").permitAll()
// .requestMatchers(HttpMethod.POST,"/api/auth/**").permitAll()
.requestMatchers("/home").permitAll()
.anyRequest().authenticated())
.addFilterBefore(new JwtTokenValidationFilter(), BasicAuthenticationFilter.class)
.httpBasic(HttpBasicConfigurer::disable)
//// .csrf(AbstractHttpConfigurer::disable)
//// .cors(corsConfigurer -> corsConfigurer
//// .configurationSource(request -> {
//// CorsConfiguration cors = new CorsConfiguration();
//// cors.setAllowedOrigins(List.of("http://localhost:3000"));
//// cors.setAllowedMethods(List.of("*"));
//// cors.setAllowCredentials(true);
//// cors.setAllowedHeaders(List.of("*"));
//// cors.setExposedHeaders(List.of("Authorization"));
//// cors.setMaxAge(3600L);
//// return cors;
//// }))
.build();
// return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我可以进一步提供 JWTUtil 和 JWTValidation 类。
@RestController
public class HomeController {
@GetMapping("/home")
public String homeController() {
return "Hello from Home";
}
}
我尝试创建自定义 SecurityFilterChain 并使用 JWT 进行身份验证。 我已经寻找了 StackOverflow 上已经存在的解决方案,但它们非常旧。但仍然不知道我错过了什么。
我一年前也遇到过同样的问题。使用 antMatchers 而不是 requestMatchers 为我做到了。