当向应用程序中不存在的端点发送post请求时,服务器返回405而不是404。对于具有现有端点的请求,也会出现类似问题,只要一切正常,但出现内部服务器错误时(例如,找不到用户),状态码将返回200,http响应变为405(而不是500)。对于get请求,一切都正常工作。
奇怪的是,如果我安装了调试器,并遵循抛出错误的过程,它将处理500个错误。但很明显,最后某个地方出了问题,我得到了405的回报。
我的web安全配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private UserDetailsService jwtUserDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Value("${allowedOrigin}")
private String origin = "http://localhost:4200";
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//You can enforce the use of HTTPS when your app is running on Heroku by adding
// the following configuration to your Spring Boot app.
httpSecurity.requiresChannel()
.requestMatchers(r - > r.getHeader("X-Forwarded-Proto") != null)
.requiresSecure();
httpSecurity
.cors()
.and().csrf()
.disable()
// dont authenticate this particular request
.authorizeRequests()
.antMatchers("/api/authenticate")
.permitAll()
// all other requests for /api need to be authenticated
.antMatchers("/api/**", "/admin/**")
.authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
更新:
我没有任何ControllerAvice,也没有编写全局异常处理程序。
405响应中的“allow”头读取“get,head”,即使post请求实际进入post端点。
2条答案
按热度按时间vojdkbi01#
根据您的httpsecurity配置,您只允许post请求,对于get、put等其他http方法,您将获得405(不允许使用方法)。。。。
yhuiod9q2#
原来是一个errorcontroller使用“/error”路径的未实现方法导致了问题。无论何时抛出异常或错误,它都被解析为“/error”,并由errorcontroller拾取,由于某种原因,它将其解析为405。实现该方法后,http状态将正确返回。