【问题标题】:Laravel and CORS with barryvdh/laravel-corsLaravel 和 CORS 与 barryvdh/laravel-cors
【发布时间】:2015-09-30 00:25:00
【问题描述】:

我在 Laravel 中遇到了一个奇怪的问题,我已经为此苦苦挣扎了一天多。它与我看到的关于 laravel-cors 包的其他帖子不同,例如这个: Laravel angularJS CORS using barryvdh/laravel-cors

我已经按照说明设置了包,我为 Laravel 添加的唯一其他内容是 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'));
    }
}

【问题讨论】:

  • 我建议你自己实现一个cors中间件,而不是使用barryvdh/laravel-cors。如果您有兴趣,请告诉我,我会将其作为答案发布。
  • 我正在考虑这样做,但我认为这不仅仅是设置访问“*”那么简单,我了解到您需要考虑“预检”请求。期待答案。

标签: laravel cors


【解决方案1】:

从 CSRF 保护中排除您的路由组。 app/Http/Middleware/VerifyCsrfToken.php

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/v1/*'
    ];
}

;)

【讨论】:

    猜你喜欢
    • 2014-06-01
    • 2015-02-19
    • 2014-12-21
    • 2018-05-07
    • 2020-07-15
    • 2017-04-20
    • 1970-01-01
    • 2016-02-14
    • 2015-04-12
    相关资源
    最近更新 更多