gpt4 book ai didi

java - Spring CORS错误

转载 作者:行者123 更新时间:2023-12-02 12:30:10 25 4
gpt4 key购买 nike

我正在使用 Spring 构建 WebApi,并使用 Reactjs 构建客户端。我正在尝试针对 WebApi 执行 POST 请求以使用 OAuth2 进行身份验证,但我不断收到

Response for preflight has invalid HTTP status code 401

WebSecurityConfigurerAdapter:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(false); //updated to false
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/**").authenticated()
.and()
.httpBasic();
}
}

我的要求是:

fetch( 
this.getAuthEndpoint('password'), {
method:'post',
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': 'Basic dG9ucjpzZWNyZXQ='
},
body: JSON.stringify({
'password': credentials.password,
'username': credentials.username,
'grant_type': 'password',
'scope': 'read write',
'client_secret': Config.clientSecret,
'client_id': Config.clientId
})})
.then(response => {
this.saveTokens(response.data);

return axios.get(Config.apiUrl + '/me');
})
.then(response => {
this.loginSuccess(response.data.user);
})
.catch(response => {
this.loginError(response);
});

请求/响应状态为: enter image description here

最佳答案

尝试执行 http.cors().. 就像

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()....
}

引用https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

这将添加 CORS 过滤器并立即返回,而不是将请求传递到安全过滤器。

关于java - Spring CORS错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45310596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com