使用nginx启用和验证CORS



我正试图通过启用nginx web服务器和proxpass请求到后端基于flask的应用程序来理解和测试CORS功能。以下是详细信息。

  1. 后端flask App
[admin@fedser flask]$ cat postjson.py 
from flask import Flask, request
app = Flask(__name__)
@app.route('/postjson', methods=['POST'])
def process_json():
content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
json = request.json
return json
else:
return 'Content-Type not supported!'

JSON数据示例

[admin@fedser flask]$ cat postdata.json 
{
"name": {
"firstname": "Alice",
"middlename": "Wonder",
"lastname": "land"
},
"age": 20,
"gender": "Male"
}

启动flask应用程序

[admin@fedser flask]$ flask --app postjson run --host=fedser.stack.com --port=2121 &
  1. 在nginx上使用proxypass和restart service启动CORS
[admin@fedser nginx]$ cat nginx.conf
...
server {
location /proxyflask {
add_header Access-Control-Allow-Origin "fedser.stack.com";
proxy_pass http://fedser.stack.com:2121/postjson;
}
}
...
  1. Test CORS feature

根据我对CORS特性的理解,如果请求来自相同的来源,在我的情况下,来源是"fedser.stack.com"如下所示:

[admin@fedser flask]$ curl -X POST -H "Content-type: application/json" 'http://fedser.stack.com/proxyflask' -d @postdata.json -v
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 192.168.29.117:80...
* Connected to fedser.stack.com (192.168.29.117) port 80 (#0)
> POST /proxyflask HTTP/1.1
> Host: fedser.stack.com
> User-Agent: curl/7.85.0
> Accept: */*
> Content-type: application/json
> Content-Length: 106
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.22.1
< Date: Wed, 05 Apr 2023 02:58:58 GMT
< Content-Type: application/json
< Content-Length: 96
< Connection: keep-alive
< Access-Control-Allow-Origin: fedser.stack.com
< 
{"age":20,"gender":"Male","name":{"firstname":"Alice","lastname":"land","middlename":"Wonder"}}
* Connection #0 to host fedser.stack.com left intact

但是如果我把Origin改成"example.com"通过设置报头,我假设它应该阻止我的请求,按照我启用的cors限制,但它不会这样发生。

[admin@fedser flask]$ curl -X POST -H "Content-type: application/json" -H "Origin: http://example.com" 'http://fedser.stack.com/proxyflask' -d @postdata.json -v
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying 192.168.29.117:80...
* Connected to fedser.stack.com (192.168.29.117) port 80 (#0)
> POST /proxyflask HTTP/1.1
> Host: fedser.stack.com
> User-Agent: curl/7.85.0
> Accept: */*
> Content-type: application/json
> Origin: http://example.com
> Content-Length: 106
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx/1.22.1
< Date: Wed, 05 Apr 2023 02:46:05 GMT
< Content-Type: application/json
< Content-Length: 96
< Connection: keep-alive
< Access-Control-Allow-Origin: fedser.stack.com
< 
{"age":20,"gender":"Male","name":{"firstname":"Alice","lastname":"land","middlename":"Wonder"}}
* Connection #0 to host fedser.stack.com left intact

如果我在这里遗漏了什么,请让我知道我对cors的理解。

您的配置是正确的

根据这个链接:

CORS机制支持浏览器和服务器之间的安全跨域请求和数据传输。

所以你不能在curl中产生错误。

相关内容

  • 没有找到相关文章

最新更新