突然无法从 localhost:3000 向 localhost:5000 发送请求
我的项目使用 Springboot 后端和 React 前端。突然间,请求停止工作。我已经使用这个项目几个月了。
这是失败的请求:
// authenticate
// API_BASE_URL in this case is http://localhost:5000/api/
async authenticateUser(user) {
return axios.post(API_BASE_URL + "authenticate", user).catch((error) => {
console.log("failed to authenticate user: " + error);
throw new Error("failed to authenticate user");
});
}
该端点的后端代码如下所示:
@PostMapping("/api/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationRequest.getEmail(), authenticationRequest.getPassword()));
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password");
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getEmail());
final String jwt = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(jwt));
}
这是我的 SecurityConfiguration
类:
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
MongoUserDetailsService userDetailsService;
@Autowired
private JwtTokenFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers("/", "/api/register",
"/api/authenticate", "/api/test")
.permitAll().anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
// create bean of type 'authenticationManager'
return super.authenticationManagerBean();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration config = new CorsConfiguration();
config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
添加照片,以便您可以直观地看到问题。
My project uses a Springboot backend and React frontend. All of a sudden, the requests stopped working. I have been using this project for months.
This is the request that is failing:
// authenticate
// API_BASE_URL in this case is http://localhost:5000/api/
async authenticateUser(user) {
return axios.post(API_BASE_URL + "authenticate", user).catch((error) => {
console.log("failed to authenticate user: " + error);
throw new Error("failed to authenticate user");
});
}
The backend code for that endpoint looks like this:
@PostMapping("/api/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationRequest.getEmail(), authenticationRequest.getPassword()));
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password");
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getEmail());
final String jwt = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthenticationResponse(jwt));
}
And this is my SecurityConfiguration
class:
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
MongoUserDetailsService userDetailsService;
@Autowired
private JwtTokenFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers("/", "/api/register",
"/api/authenticate", "/api/test")
.permitAll().anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
// create bean of type 'authenticationManager'
return super.authenticationManagerBean();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration config = new CorsConfiguration();
config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
Adding photos so that you can see the issues visually.
As you can see in the image below, its failing the Preflight, but why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜我的
AuthenticationController
类上的@CrossOrigin(origins = { "*" })
没有按预期工作。为了解决这个问题,我将行
config.setAllowedOrigins(Arrays.asList("*"));
添加到corsConfigurationSource
中,如下所示:I guess the
@CrossOrigin(origins = { "*" })
that I have on myAuthenticationController
class was not working as expected.To fix, I added the line
config.setAllowedOrigins(Arrays.asList("*"));
to thecorsConfigurationSource
so that it looks like this: