I am facing up this problem:
I set CORS headers in nginx, in this way:
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";
I need to call my API endpoint to authenticate an user and release a JWT. What is happening is that if the authentication goes fine, the server respond with the following headers:
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
But, if credentials are invalid, I get these ones:
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
In other words, correct credentials give me a 200 status code with CORS headers, while wrong credentials give me 401 status code without CORS headers
Here is the auth method of User controller:
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. i am testing with Postman, but the actual problem is that without CORS headers I can't read the response in browser (which uses XHR through React fetch
)