我在Laravel中遇到一个奇怪的问题,我现在已经挣扎了一天多了。它与我见过的关于laravel-cors包的其他帖子有所不同,例如: Laravel angularJS CORS using barryvdh/laravel-cors
我已根据说明设置了包装,而Laravel I制作的唯一其他添加是JWT的包装。
正在发生的事情是CORS仅在POST请求中工作。我可以使用POSTMAN来查看我的身份验证路由,一切看起来都不错,但是一旦我尝试任何GET请求,就不会发送任何CORS头。我尝试将不同的控制器移动到我未受保护的控制器上。路线以消除JWT干扰的可能性,但这并没有改变任何事情。
这是我的routes.php:
<?php
// unprotected routes
Route::group(['prefix' => 'api/v1', 'middleware' => 'cors'], function () {
Route::post('authenticate', 'AuthenticateController@authenticate');
Route::resource('trips', 'TripController'); // moved to unprotected to test CORS
});
// protected routes
Route::group(['prefix' => 'api/v1', 'middleware' => ['cors', 'jwt.auth']], function () {
Route::get('authenticate/user', 'AuthenticateController@getAuthenticatedUser');
Route::resource('airports', 'AirportController');
});
我的cors.php:
<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value, the allowed methods however have to be explicitly listed.
|
*/
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'POST', 'PUT', 'OPTIONS', 'DELETE'],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],
];
我的一个控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
// verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
public function getAuthenticatedUser()
{
try {
if (!$user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
}
答案 0 :(得分:0)
从CSRF保护中排除您的路线组。 应用程序/ HTTP /中间件/ VerifyCsrfToken.php
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'api/v1/*'
];
}
)