我收到错误:OPTIONS http://10.100.8.58:8080/user/view 401(),

时间:2018-05-04 05:47:59

标签: java angular http spring-security cors

我的服务器端代码是..

public class SimpleCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;



    response.setHeader("Access-Control-Allow-Origin", "*");


    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("X-Frame-Options", "*");
        response.setHeader("Access-Control-Allow-Headers", "content-type,access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
}

@Override
public void destroy() {

}

}

我的客户端代码是......

viewUsers(): Observable<any> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');       
    headers.append('Access-Control-Allow-Origin', '*')
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic dXNlcjpzdXJpeWFu');

    let options = new RequestOptions({ headers: headers });

    return this.http.get(myurl, options).map(getJson);
}

请帮我解决这个问题...... 我遇到错误:无法加载http://10.100.8.58:8080/user/view:预检的响应包含无效的HTTP状态代码401.我不知道我在哪里犯了错误。

我的服务器端securityConfif CLass是..

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("suriyan").roles("USER").and().withUser("admin")
            .password("suriyans").roles("USER", "ADMIN");
}

protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().antMatchers("/user/**").hasRole("USER").antMatchers("/**")
            .hasRole("ADMIN").and().csrf().disable().headers().frameOptions().disable();
}

}

我的帖子man代码是..

 OkHttpClient client = new OkHttpClient();

 Request request = new Request.Builder()
 .url("http://10.100.8.58:8080/user/view")
 .get()
 .addHeader("authorization", "Basic dXNlcjpzdXJpeWFu")
 .addHeader("cache-control", "no-cache")
 .addHeader("postman-token", "48b3ca10-fe72-4a1e-ce00-44c78afb636a")
 .build();

 Response response = client.newCall(request).execute();

1 个答案:

答案 0 :(得分:0)

您的请求由浏览器预检,因为同源政策。我认为this is a good description关于 SOP CORS

为了允许来自不同来源的http请求,您必须启用 CORS ,但这是使用标头在服务器上完成的:

Access-Control-Allow-Origin: '*'

您已在客户端上声明此标头,我认为这是错误的。 这里有一些关于使用Spring启用 CORS 的示例:

Spring CORS No 'Access-Control-Allow-Origin' header is present

https://spring.io/guides/gs/rest-service-cors/