[zeromicro/go-zero]服务上线,误传headers.Authorization导致CORS跨域失败

2023-12-20 267 views
6

*.api 没有引入 jwt

service ***-api {
// code
}

nginx 配置 [测试]


location /v3/ {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
return 200;
}
    rewrite ^/v3/(.*)$ /$1 break;
    proxy_pass http://localhost:20103;
}
> nginx 配置[部署]

location /v3/ {

    if ($request_method = 'OPTIONS') {
        add_header Cache-Control private;
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Max-Age' 86400;
        add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Token,DNT,Content-Type,Cache-Control,User-Agent,Keep-Alive,Authorization,authorization,beid,ptyid';
        return 204;
    }

    add_header 'Access-Control-Allow-Origin' *;
    add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token';

    rewrite ^/v3/(.*)$ /$1 break;
    proxy_pass http://localhost:20103;
}
> 接口请求请参考以下代码

<!DOCTYPE html>

Document

#### 我的问题如下:
+ 我的api并没有引入jwt,理论上应该不会对header进行校验(自己瞎猜的),但使用header参数,会导致 CORS错误,如何优雅处理。
+ 如果nginx不进行header处理,有什么办法能够避免这个问题?
+ 测试接口: https://www.cakioe.com/v3/

回答

0

测试了下缺一个 Access-Control-Allow-Headers 的配置,GET 请求加了特殊 Header 之后会变成 复杂请求 ,会有 OPTIONS 先行,如果不带这个 Authorization 的话,是 简单请求 ,不会触发 OPTIONS

image

6

找个带 jQuery 的非同源网站,比如 baidu.com ,Chrome 的 console 直接执行如下代码可以比较方便的测试这个问题:

$.ajax({url: "https://www.cakioe.com/v3/enneagrams/14", beforeSend: (xhr) => xhr.setRequestHeader("Authorization", "Bearer 2123123")})
5

@svcg 请问下最后怎么解决的?

6

如此

if ($request_method = 'OPTIONS') {
    add_header Cache-Control private;
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Max-Age' 86400;
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,UPDATE,DELETE,PUT';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With';
    return 204;
}
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,UPDATE,DELETE,PUT';
add_header Access-Control-Allow-Headers 'Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With';

这样