2017-07-25 131 views
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); 
     }); 

而且请求/响应状态是: enter image description here

回答