Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3619

405 method not allowed Spring Boot API and Angular

$
0
0

in one of my Spring API projects I sometimes encounter a "405 method not allowed" error if I use the PUT call. The error is quite random, sometimes the call works without problems, sometimes it fails and goes back to working without making any changes to the backend code. I encounter the problem only when using an Angular front end, while not from any other client (e.g. Postman).

Inside the project there is a WebMvcConfigurer:

@Configuration@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {    registry.addMapping("/**")            .allowedOrigins("*")            .allowedMethods("*");}}

And spring security is being used with this configuration:

@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)public class SecurityConfiguration extends GlobalMethodSecurityConfiguration  {@Value("${jwt.public.key}")RSAPublicKey publicKey;@Value("${jwt.private.key}")RSAPrivateKey privateKey;/** * This bean is used to configure the JWT token. Configure the URLs that should not be protected by the JWT token. * * @param http the HttpSecurity object * @return the HttpSecurity object * @throws Exception if an error occurs */@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {    //@formatter:off    http            .authorizeHttpRequests(authorizeRequests -> authorizeRequests                    .requestMatchers("/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html","/api-docs/**","/weblocation/**","/webquestion/**","/webmultiplechoicequestion/**","webmultiplechoiceoption/**").permitAll()                    .anyRequest()                    .authenticated())            .cors(cors -> cors.disable())            .csrf(AbstractHttpConfigurer::disable)            .formLogin(AbstractHttpConfigurer::disable)            .httpBasic(AbstractHttpConfigurer::disable)            .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))            .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()))            .exceptionHandling(exceptions -> exceptions                    .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())                    .accessDeniedHandler(new BearerTokenAccessDeniedHandler())            );    //@formatter:on    return http.build();}/** * This bean is used to decode the JWT token. * * @return Returns the JwtDecoder bean to decode JWT tokens. */@BeanJwtDecoder jwtDecoder() {    return NimbusJwtDecoder.withPublicKey(this.publicKey).build();}/** * This bean is used to encode the JWT token. * * @return Returns the JwtEncoder bean to encode JWT tokens. */@BeanJwtEncoder jwtEncoder() {    JWK jwk = new RSAKey.Builder(this.publicKey).privateKey(this.privateKey).build();    return new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(jwk)));}@Bean(name="passwordEncoder")@Autowired PasswordEncoder passwordEncoder() {    return new BCryptPasswordEncoder();}}

While this is the call in the controller:

@PutMapping(path = "/weblocation/{id}")public @ResponseBody WebLocationDTO patch_fields_of_weblocation(Authentication authentication,                                                                @Parameter(description="WebLocation ID") @PathVariable(name="id") Long id,                                                                @Parameter(description="Fields to be updated") @RequestBody(required=true) Map<String, Object> fields_to_be_updated){    ......}

I also tried changing the Security as follows, but without solving the problem:

@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {    //@formatter:off    http        .authorizeHttpRequests(authorizeRequests -> authorizeRequests            .requestMatchers("/auth/**", "/swagger-ui-custom.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html","/api-docs/**").permitAll()            .requestMatchers(HttpMethod.PUT, "/weblocation/**").permitAll()            .requestMatchers(HttpMethod.PATCH, "/weblocation/**").permitAll()            .requestMatchers("/weblocation/**", "/webquestion/**", "/webmultiplechoicequestion/**", "/webmultiplechoiceoption/**").permitAll()            .anyRequest().authenticated()        )        .cors(cors -> cors.disable())        .csrf(AbstractHttpConfigurer::disable)        .formLogin(AbstractHttpConfigurer::disable)        .httpBasic(AbstractHttpConfigurer::disable)        .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))        .exceptionHandling(exceptions -> exceptions            .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())            .accessDeniedHandler(new BearerTokenAccessDeniedHandler())        );    //@formatter:on    return http.build();}

This is the front end call in angular:

async patchWebLocationById(id: number, surveyDetails: Partial<Survey>): Promise<Survey> {try {  const response: AxiosResponse<Survey> = await axios.put(`${this.baseUrl}/weblocation/${id}`, surveyDetails, {    headers: this.getHeaders(),  });  return response.data;} catch (error) {  console.error(`Error updating survey with ID ${id}:`, error);  throw error;}

}

What causes the random 405 error? Suggestions to fix this problem?

Thanks

Please note: calls are authorized via JWT Token issued after login with user and password


Viewing all articles
Browse latest Browse all 3619

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>