0
我正在用Spring和客戶端用Reactjs構建WebApi。我試圖做一個POST請求與的OAuth2認證,反對的WebAPI,但我不斷收到預檢春季CORS錯誤
響應具有無效的HTTP狀態碼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);
});