我正在开发一个 spring-boot Web 应用程序,并已使用 JWT 配置了 Spring Security。我的问题是,当我在 Postman 中发出 POST 请求时,收到 401 未经授权的错误。但是,当我发出 GET 请求时,它返回状态为 200 的数据。这似乎是一个常见问题;我检查了 stackoverflow 上的不同线程,大多数建议在安全配置中禁用 CSRF。我已经这样做了,但还是不行。
使用 PermitAll() 请求“/courses/**”,无需身份验证即可访问。
SecurityConfig.java
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final CustomUserDetailsService userDetailsService;
private final JwtAuthEntryPoint jwtAuthEntryPoint;
@Bean
public AuthTokenFilter authenticationTokenFilter(){
return new AuthTokenFilter();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public DaoAuthenticationProvider authenticationProvider(){
var authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http.csrf(AbstractHttpConfigurer::disable) // Disable CSRF for stateless APIs
.exceptionHandling(exception -> exception.authenticationEntryPoint(jwtAuthEntryPoint))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth->
auth.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/roles/**").permitAll()
.requestMatchers("/api/users/**").permitAll()
.requestMatchers("/courses/**").permitAll()
.anyRequest().authenticated()
);
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
发帖方法
@PostMapping("/add-course")
public ResponseEntity<?> addCourse(@RequestBody Course course){
try{
System.out.println("Course body: " + course);
Course theCourse = courseService.addNewCourse(course);
return ResponseEntity.ok(theCourse);
}catch (Exception e){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
Postman API 调用图片
考虑通过暂时允许所有请求 (.requestMatchers("/").permitAll()) 来测试 POST 请求,以查看问题是否仍然存在。这可以帮助确定问题是否特定于您的 /courses/ 配置。