最佳做法处理Spring和角度JS之间CORS? [英] Best practices for handling CORS between Spring and Angular JS?

查看:118
本文介绍了最佳做法处理Spring和角度JS之间CORS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用的是Java春季为构建REST API。而我们使用的是angularjs的前端。该REST API是在一个域和angularjs在另一个领域。最初,当我试图做从角度到REST API一个POST请求时,它给了CORS错误。然后,我们通过在后端设置CORS过滤器解决了这个问题。但是,当我们试图做一个GET请求时,它抛出401未经授权错误。这是因为,我们的GET请求是不 - 一个简单的请求为要求具有内容类型为application / JSON和头部有'授权'(因为我们使用的基本auhentication)。因此,浏览器发送一个preflight选项请求发送GET请求之前的服务器。因此401错误抛出的选项要求由Spring安全通过拦截的URL。那是因为在选项的要求可是没有任何凭据。因此,要解决这个问题,我们已经把方法=在弹簧security.xml文件GET,在拦截的URL。这已经解决了该问题。但是,这是一个很好的做法,在指定的网址拦截的方法?也就是我们下面的过程中,一个好的做法呢?

We are using Java Spring for building a rest api. And we are using angularjs for frontend. The rest api is in one domain and the angularjs is in another domain. Initially, when i tried to do a 'POST' request from angular to the rest api, it gave CORS error. Then we resolved this issue by setting up CORS filter at the backend. But when we tried to do a get request, it is throwing 401 unauthorized error. That's because, our get request is 'not-a-simple-request' as the request has content-type as application/json and headers have 'Authorization' (since we are using basic auhentication). So the browser sends a preflight 'OPTIONS' request to the server before sending the 'GET' request. And hence the 401 error is thrown for the 'OPTIONS' request by the Spring security by intercepting the url. And that's because the 'OPTIONS' request doesnt have any credentials. So to overcome this issue, we have placed method="GET" in intercept url in spring-security.xml. This has fixed the issue. But is this a good practice, specifying method in intercept url? And also is the process we are following, a good practice?

推荐答案

我不知道这是否是最好的做法,但我们有同样的问题,并专门设置ROLE_ANONYMOUS在OPTIONS方法<固定它code>弹簧security.xml文件:

I don't know if it's the best practice, but we had the same issue and fixed it by setting the ROLE_ANONYMOUS specifically for the OPTIONS method in the spring-security.xml:

<intercept-url pattern="/users" method="OPTIONS" access="ROLE_ANONYMOUS"/>

这篇关于最佳做法处理Spring和角度JS之间CORS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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