REST API - CORS Problems

可紊 提交于 2020-01-25 08:34:15

问题


CORS is being a problem for me..

I made a REST API with SPRING on http://localhost:8080 and I used to use this API with a plain JS site on http://localhost, but after apply OAuth2 the following error started to bother me.

Access to XMLHttpRequest at 'http://localhost:8080/oauth/token' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I could access the API without CORS problems before OAuth (with AJAX and POSTMAN), and after apply OAuth I could use the API just on POSTMAN, but I couldn't do the same with AJAX.

My AJAX code:

function pronta(){
    var username = "postmain"; // yes, I wrote wrong
    var password = "1234";  

    function make_base_auth(user, password) {
      var tok = user + ':' + password;
      var hash = btoa(tok);
      return "Basic " + hash;
    }
    $.ajax
      ({
        type: "POST",
        url: "http://localhost:8080/oauth/token",
        dataType: 'json',
        data: {
            'grant-type': 'password',
            'username': 'Tiago',
            'password': '123'
        },
        header:{'Authorization': make_base_auth(username, password)}, // I've tried on both manners. with header and with beforeSend
        beforeSend: function (xhr){ 
            xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
        },
        success: function (){
            alert('done'); 
        }
    });
}

My CORS Filter (on SPRING REST API)

    @Component
    public class SimpleCORSFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}

}

The filter was working well before OAuth

Some ideas what's happening?

Tks


回答1:


I got it.. The problem was everytime I was trying to make a request, a preflight request was subimited before (like REST architecture is designed to do).

Taking this into account I just prepare the server to permit OPTIONS methods.

Like this..

@Order(-1)    
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll();
    }

Do not forget @Configuration annotation before class starting.

See ya




回答2:


It might be help:

@Component
    public class SimpleCORSFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

   if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(request, response);
        }

    }

@Override
public void init(FilterConfig filterConfig) {}

@Override
public void destroy() {}

}


来源:https://stackoverflow.com/questions/53889509/rest-api-cors-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!