Laravel 5 / Nginx - 在Web服务器级别设置的CORS标头的奇怪行为

时间:2016-03-17 17:28:07

标签: php nginx laravel-5 http-headers cors

我正面临这个问题:

我在nginx中设置了CORS头,这样:

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET,POST,PUT,OPTIONS";
add_header Access-Control-Allow-Headers "Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type";

我需要调用我的API端点来验证用户身份并发布JWT。发生的事情是,如果身份验证正常,服务器将使用以下标头进行响应:

Access-Control-Allow-Headers →Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type
Access-Control-Allow-Methods →GET,POST,PUT,OPTIONS
Access-Control-Allow-Origin →*
Cache-Control →no-cache
Connection →keep-alive
Content-Encoding →gzip
Content-Type →application/json
Date →Thu, 17 Mar 2016 17:13:34 GMT
Server →nginx
Strict-Transport-Security →max-age=10886400; includeSubdomains
Transfer-Encoding →chunked
Vary →Accept-Encoding
X-Content-Type-Options →nosniff
X-Frame-Options →SAMEORIGIN
X-XSS-Protection →1; mode=block

但是,如果凭据无效,我会收到这些

Cache-Control →no-cache
Connection →keep-alive
Content-Encoding →gzip
Content-Type →application/json
Date →Thu, 17 Mar 2016 17:14:58 GMT
Server →nginx
Transfer-Encoding →chunked
Vary →Accept-Encoding

换句话说,正确的凭据为我提供了带有CORS标头的200状态代码,而错误的凭据为我提供了401状态代码,没有 CORS标头

以下是用户控制器的auth方法:

public function authenticate(Requests\AuthenticateUserRequest $request)
    {
        $credentials = $request->only('username', 'password');
        $customClaims = ['tfa' => null];

        try
        {
            // attempt to verify the credentials and create a token for the user
            if (!$token = JWTAuth::attempt($credentials, $customClaims))
            {
                // when this is the response, CORS headers are not set by nginx 
                return response()->json(Utils::standardResponse(false, 'Invalid credentials'), 401);
            }
        } catch (JWTException $e)
        {
            // something went wrong whilst attempting to encode the token
            return response()->json(Utils::standardResponse(false, 'Could not create token'), 500);
        }

       [...email notification and other stuff...]

        // all good so return the token
        return response()->json(Utils::standardResponse(true, '', compact('token')));
    }

N.B。我正在使用Postman进行测试,但实际问题是没有CORS标题我无法在浏览器中读取响应(通过React fetch使用XHR)

1 个答案:

答案 0 :(得分:0)

想通了。 Nginx add_header仅在成功回复时设置标题 (200状态代码)。

我确实需要使用headers_more nginx的模块。特别是,我做了:

more_set_headers "Access-Control-Allow-Origin: *";
more_set_headers "Access-Control-Allow-Methods: GET,POST,PUT";
more_set_headers "Access-Control-Allow-Headers: Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type";

正如文档中所建议的那样,

  

如果未指定-s或-t或具有空列表值,则   不需要匹配。因此,以下指令设置   服务器输出标头为任何状态代码和任意的自定义值   内容类型:

     

more_set_headers "Server: my_server";