如何配置Spring Security解决Angular发送PUT请求返回405错误的问题
问题根因及解决方法
你遇到的405错误由两个常见原因导致,按优先级排查:
1. 请求路径不匹配
你的Angular端PUT请求发往的地址是http://localhost:8080/api/heroes,但后端@PutMapping注解配置的路径是/{id},需要在URL末尾拼接要更新的资源ID才能匹配到对应接口。路径不匹配时Spring无法找到对应的PUT接口映射,就会返回405错误,响应头的Allow字段仅返回当前路径下已注册的GET、POST方法。
修复方案:修改Angular端PUT请求的URL,拼接英雄ID:
/** PUT: update the hero on the server */ updateHero(hero: Hero): Observable<any> { return this.http.put(`${this.heroesUrl}/${hero.id}`, hero, this.httpOptions).pipe( tap(_ => this.log(`updated hero id=${hero.id}`)), ); }
2. Spring Security默认配置拦截PUT请求
Spring Security默认开启CSRF防护,会拦截POST之外的修改类请求(PUT、DELETE、PATCH等),同时默认的权限规则也可能限制了PUT方法的访问。
修复方案:新增Spring Security配置类,调整相关规则:
@Configuration @EnableWebSecurity class SecurityConfig : WebSecurityConfigurerAdapter() { override fun configure(http: HttpSecurity) { http // 前后端分离使用Basic Auth的场景可直接关闭CSRF防护 .csrf().disable() .authorizeRequests() // 配置/api/heroes路径下的PUT请求只要完成认证即可访问 .antMatchers(HttpMethod.PUT, "/api/heroes/**").authenticated() .anyRequest().authenticated() .and() // 保留你的Basic Auth配置 .httpBasic() } }
如果你的Spring Boot版本是2.7+,WebSecurityConfigurerAdapter已废弃,可以改用SecurityFilterChain的配置方式:
@Configuration @EnableWebSecurity class SecurityConfig { @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http .csrf { it.disable() } .authorizeHttpRequests { it.antMatchers(HttpMethod.PUT, "/api/heroes/**").authenticated() it.anyRequest().authenticated() } .httpBasic(Customizer.withDefaults()) return http.build() } }
完成以上两处修改后PUT请求即可正常处理。
内容的提问来源于stack exchange,提问作者hmc
相关产品推荐
相关产品推荐

