4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel: 開発時だけ他ホストからの要求を許可する (CORS)

Last updated at Posted at 2019-10-25

背景

開発時のみフロントエンドを別ホスト・ポートで動作し、クロスサイトでのリクエストを許可したい。本番には適用しない。

実装

CORS ヘッダを設定するミドルウェアを作成する。

クロスサイトで認証情報つき(withCredentials)リクエストをおこないたい場合は Access-Control-Allow-Origin: * が許可されないため、リクエスト元のホスト名を入れて返している。
参考) Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Cors
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var Response $response */
        $response = $next($request);

        if (env('APP_DEBUG') && $request->header('Origin')) {
            $response->headers->set('Access-Control-Allow-Credentials', 'true');
            $response->headers->set('Access-Control-Allow-Origin', $request->header('Origin'));
            $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            $response->headers->set('Access-Control-Allow-Headers', 'Origin, Authorization, Accept, Content-Type, X-XSRF-Token');
            $response->headers->set('Access-Control-Expose-Headers', 'Authorization');
        }

        return $response;
    }
}

このミドルウェアを有効にする。

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    ...
    protected $middleware = [
        ...
        \App\Http\Middleware\Cors::class
    ];
    ...
}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?