【发布时间】:2020-08-04 17:01:00
【问题描述】:
我在 Heroku 上托管后端,在 Netlify 上托管前端。当我在后端调用端点时,它会发送预检选项,但会给出 403 状态。 我确实搜索了解决方案,但它仍然无法正常工作。
我希望能够使用"POST" 方法调用"/authenticate" 端点,其主体从FE 到BE。
Spring 安全配置(只是配置方法)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
...
@Override
public void configure(WebSecurity web) throws Exception
{
web.ignoring()
.antMatchers(HttpMethod.POST, "/authenticate", "/register")
.antMatchers(HttpMethod.GET, "/token")
.antMatchers("/h2-console/**")
.antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/authenticate").permitAll()
.antMatchers(HttpMethod.GET, "/user-data").authenticated()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of(<MY-URL>));
configuration.setAllowedHeaders(List.of("*"));
configuration.setMaxAge(Long.valueOf(3600));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
并从 FE 调用
var req = new XMLHttpRequest();
req.open('POST', API_URL + '/authenticate', true);
req.setRequestHeader("Content-Type", "application/json");
req.withCredentials = true;
req.onreadystatechange = function (aEvt) {
if (req.readyState === 4) {
if(req.status === 200) {
console.log(req.responseText);
isAuthenticationSucessful = true;
}
else
console.log("Error loading site");
}
};
req.send(JSON.stringify({username, password}));
浏览器开发工具:
Reason: CORS header 'Access-Control-Allow-Origin' missing
Reason: CORS request did not succeed
【问题讨论】:
-
将安全配置为
http.cors().configurationSource(corsConfigurationSource()).and()... -
@HMD 谢谢!同样在
setAllowedOrigins()我放了myurl.com/,但是浏览器使用Origin: myurl.com发送请求而没有斜杠,这也是需要修复的地方 -
@HMD 我太快了。这并不能解决我所有的问题。它正在发送成功的请求,但浏览器不接受响应。但我让它起作用了,如果你愿意,你可以查看我的答案。再次感谢,您的评论帮助我朝着正确的方向前进。
标签: spring spring-security cors