REST API-CORS问题 [英] REST API - CORS Problems

查看:146
本文介绍了REST API-CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CORS对我来说是个问题.

CORS is being a problem for me..

我在 http://localhost:8080 上使用SPRING制作了REST API,并且我以前经常将此API与 http://localhost 上的纯JS网站,但是在应用OAuth2之后,以下错误开始困扰我.

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.

从原始位置通过 http://localhost:8080/oauth/token 访问XMLHttpRequest " http://localhost "已被CORS策略阻止:对预检请求的响应未通过访问控制检查:没有HTTP正常状态

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

在OAuth(使用AJAX和POSTMAN)之前,我可以访问API而没有CORS问题,并且在应用OAuth之后,我可以仅在POSTMAN上使用API​​,但是我不能对AJAX进行相同操作.

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.

我的AJAX代码:

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'); 
        }
    });
}

我的CORS过滤器(基于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() {}

}

该过滤器在OAuth之前运行良好

The filter was working well before OAuth

一些想法正在发生什么?

Some ideas what's happening?

Tks

推荐答案

我明白了. 问题是每次我尝试发出请求时,都会先发出预检请求(就像REST体系结构设计那样).

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).

考虑到这一点,我只是准备允许服务器使用OPTIONS方法.

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

喜欢这个..

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

在类开始之前,请不要忘记@Configuration批注.

Do not forget @Configuration annotation before class starting.

再见

这篇关于REST API-CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆