Laravel6とLaravel8でのCORS・JWT認証の設定方法

Laravel6とLaravel8でのCORS・JWT認証の設定方法

February 13, 2021

忘れても良いように手順をメモしておきます。

Laravel6 #

1.CORS 対応 #

上記 GitHub に書いてある、「Installation, Global usage / Configuration」に従って進めれば CORS できるようになります。簡単。

2.JWT 認証対応 #

以下の手順に従ってインストール・設定します。

まずは Install の手順の「Install via composer / Publish the config / Generate secret key」に従います。ただし Composer で require する際には公式通りではなく以下のコマンドを実施します。

COMPOSER_MEMORY_LIMIT=-1 composer require tymon/jwt-auth "^1.0.0"

composer require tymon/jwt-auth とだけ実施すると、古いバージョンが入ってしまいます。また Composer 実行時のメモリ制限に引っ掛かりインストールがエラーとなることがあるため、メモリ制限を外してインストールしています。

次に、Quick Start の手順の「Update your User model / Configure Auth guard / Add some basic authentication routes / Create the AuthController」に従います。

上記実施後、 http://localhost:8000/api/auth/login など(パスは各自の環境によります)に Talend や Postman でリクエストをしてみて、以下のような結果が返れば成功です。

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
  "token_type": "bearer",
  "expires_in": 3600
}

なお、失敗した場合は以下のレスポンスが返ってきます。

{
  "error": "Unauthorized"
}

参考1:Laravel の設定ファイルの内容 #

JWT 設定後の「app/User.php」と「config/auth.php(抜粋)」を以下に載せておきます。

app/User.php #
<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// use Tymon\JWTAuth\Contracts\JWTSubject;を追加
use Tymon\JWTAuth\Contracts\JWTSubject;

// implements JWTSubjectを追加
class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    // /**
    //  * The attributes that should be hidden for arrays.
    //  *
    //  * @var array
    //  */
    protected $hidden = [
        'password', 'remember_token',
    ];

    // /**
    //  * The attributes that should be cast to native types.
    //  *
    //  * @var array
    //  */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // 以降を追加
    // https://jwt-auth.readthedocs.io/en/develop/quick-start/

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}
config/auth.php(抜粋) #
    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'api', // 'web'から変更
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'jwt', // 'token'から変更
            'provider' => 'users',
            // 'hash' => false, // 削除(コメントアウト)
        ],
    ],

参考2:Laravel へのリクエストの内容(cURL) #

1.login へのリクエスト例 #
curl -i -X POST \
   -H "Content-Type:application/json" \
   -d \
'{
  "email":  "test@test.com",
  "password": "testtest"
}' \
 'http://localhost:8000/api/auth/login'
2.logout へのリクエスト例 #
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTYxMzExNDc3MSwiZXhwIjoxNjEzMTE4MzcxLCJuYmYiOjE2MTMxMTQ3NzEsImp0aSI6IjNvZWNUa2tTeFY3MTZwQnQiLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.vCj404AO_jHVpt6F5_lcqMfv9r1pqBkxX6Y18THSLG4" \
   -d \
'' \
 'http://localhost:8000/api/auth/logout'
3.refresh へのリクエスト例 #
curl -i -X POST \
   -H "Content-Type:application/json" \
   -H "Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9hdXRoXC9yZWZyZXNoIiwiaWF0IjoxNjEzMTE0Nzg4LCJleHAiOjE2MTMxMTg0NTQsIm5iZiI6MTYxMzExNDg1NCwianRpIjoiRVVYazlDbjlYSHdpUkFUNCIsInN1YiI6MSwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.-U-zmSr0JAPaU9fxcfcwkhnCZl2ZmltA_q6xn3WmO2U" \
 'http://localhost:8000/api/auth/refresh'
4.me へのリクエスト例 #
curl -i -X GET \
   -H "Authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTYxMzEyODc4OCwiZXhwIjoxNjEzMTMyMzg4LCJuYmYiOjE2MTMxMjg3ODgsImp0aSI6IlRLdkVadjZpYlY3REUyaWIiLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.FRn6-kvZaZWZjBv1_ngHcDtStcIKkZgWc0nztmuAJMs" \
 'http://localhost:8000/api/auth/me'

Laravel8 #

1.CORS 対応 #

api.php のルーティングはデフォルトで CORS 許可されてます。そのため特に作業不要です。

Laravel can automatically respond to CORS OPTIONS HTTP requests with values that you configure. All CORS settings may be configured in your application’s config/cors.php configuration file. The OPTIONS requests will automatically be handled by the HandleCors middleware that is included by default in your global middleware stack. Your global middleware stack is located in your application’s HTTP kernel (App\Http\Kernel).

https://laravel.com/docs/8.x/routing#cors

Laravel 6 のときに、Fruitcake-Cors のモジュール入れたと思いますが、Laravel 8 にはデフォルトで入っています。詳しくは下記を見てみてください。Laravel 6 でやったのと同じ対応がすでにされていることがわかるはず。

  • config/cors.php
  • app/Http/Kernel.php -> \Fruitcake\Cors\HandleCors::class

2.JWT 認証対応 #

Sanctum(サンクタム)を使用します。公式の手順書に従って作業すれば OK です。

なお、Sanctum の認証方式は以下の2種類があります。Laravel を API のように使用する場合は、API Token Authentication 方式のほうを利用します。

  • SPA Authentication
  • API Token Authentication

以上 #

Laravel8 の方が手順が少なくより簡単ですね。現場からは以上です!