Метод 405 не разрешен Spring Boot API и AngularJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Метод 405 не разрешен Spring Boot API и Angular

Сообщение Anonymous »

В одном из моих проектов Spring API я иногда сталкиваюсь с ошибкой «405 метод не разрешен», если использую вызов PUT. Ошибка довольно рандомная, иногда вызов работает без проблем, иногда происходит сбой и возобновляется работа без внесения каких-либо изменений в бэкенд-код. Я сталкиваюсь с проблемой только при использовании интерфейса Angular, а не с каким-либо другим клиентом (например, Postman).
Внутри проекта есть WebMvcConfigurer:

Код: Выделить всё

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*");
}}
И в этой конфигурации используется Spring Security:

Код: Выделить всё

@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
*/

@Bean
public 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.
*/
@Bean
JwtDecoder 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.
*/
@Bean
JwtEncoder 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();
}

}
Пока это вызов в контроллере:

Код: Выделить всё

@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 fields_to_be_updated){
......
}
Я также пытался изменить безопасность следующим образом, но проблема не решена:

Код: Выделить всё

@Bean
public 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();
}
Это внешний вызов в angular:

Код: Выделить всё

async patchWebLocationById(id: number, surveyDetails: Partial): Promise {
try {
const response: AxiosResponse = 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;
}
Что вызывает случайную ошибку 405? Предложения по устранению этой проблемы?
Спасибо.
Обратите внимание: вызовы авторизуются с помощью токена JWT, выдаваемого после входа в систему с использованием пользователя и пароля.ЖУРНАЛ ОШИБОК ОБНОВЛЕНИЯ
Изображение


Подробнее здесь: https://stackoverflow.com/questions/786 ... nd-angular
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»