Readouble

Laravel 8.x Laravel Passport

イントロダクションIntroduction

Laravel Passportは、Laravelアプリケーションに完全なOAuth2サーバ実装を数分で提供します。Passportは、Andy MillingtonとSimon HampがメンテナンスしているLeague OAuth2 serverの上に構築されています。Laravel Passport[https://github.com/laravel/passport] provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server[https://github.com/thephpleague/oauth2-server] that is maintained by Andy Millington and Simon Hamp.

Note: note このドキュメントは、皆さんがOAuth2に慣れていることを前提にしています。OAuth2について知らなければ、この先を続けて読む前に、一般的な用語とOAuth2の機能について予習してください。{note} This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general terminology[https://oauth2.thephpleague.com/terminology/] and features of OAuth2 before continuing.

Passportか?Sanctumか??Passport Or Sanctum?

始める前に、アプリケーションがLaravel Passport、もしくはLaravel Sanctumのどちらがより適しているかを検討することをお勧めします。アプリケーションが絶対にOAuth2をサポートする必要がある場合は、Laravel Passportを使用する必要があります。Before getting started, you may wish to determine if your application would be better served by Laravel Passport or Laravel Sanctum[/docs/{{version}}/sanctum]. If your application absolutely needs to support OAuth2, then you should use Laravel Passport.

しかし、シングルページアプリケーションやモバイルアプリケーションを認証したり、APIトークンを発行したりする場合は、Laravel Sanctumを使用する必要があります。Laravel SanctumはOAuth2をサポートしていません。ただし、はるかにシンプルなAPI認証開発エクスペリエンスを提供します。However, if you are attempting to authenticate a single-page application, mobile application, or issue API tokens, you should use Laravel Sanctum[/docs/{{version}}/sanctum]. Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.

インストールInstallation

Composerパッケージマネージャにより、Passportをインストールすることからはじめましょう。To get started, install Passport via the Composer package manager:

composer require laravel/passport

Passportのサービスプロバイダは独自のデータベースマイグレーションディレクトリを登録しているため、パッケージのインストール後にデータベースをマイグレーションする必要があります。Passportのマイグレーションにより、アプリケーションがOAuth2クライアントとアクセストークンを保存するために必要なテーブルが作成されます。Passport's service provider[/docs/{{version}}/providers] registers its own database migration directory, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store OAuth2 clients and access tokens:

php artisan migrate

次に、passport:install Artisanコマンドを実行する必要があります。このコマンドは、安全なアクセストークンを生成するために必要な暗号化キーを作成します。さらに、このコマンドは、アクセストークンの生成に使用される「個人アクセス」および「パスワード許可」クライアントを作成します。Next, you should execute the passport:install Artisan command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:

php artisan passport:install

lightbulb">Tip!! 自動増分整数の代わりに、PassportのClientモデルの主キー値としてUUIDを使用したい場合は、uuidsオプションを使いPassportをインストールしてください。{tip} If you would like to use UUIDs as the primary key value of the Passport Client model instead of auto-incrementing integers, please install Passport using the uuids option[#client-uuids].

passport:installコマンドを実行し終えたら、Laravel\Passport\HasApiTokensトレイトをApp\Models\Userモデルへ追加してください。このトレイトは認証済みユーザーのトークンとスコープを調べられるように、モデルへ数個のヘルパメソッドを提供します。すでにLaravel\Sanctum\HasApiTokensトレイトを使用している場合は、それを削除してください。After running the passport:install command, add the Laravel\Passport\HasApiTokens trait to your App\Models\User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes. If your model is already using the Laravel\Sanctum\HasApiTokens trait, you may remove that trait:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

次に、App\Providers\AuthServiceProviderbootメソッド内でPassport::routesメソッドを呼び出す必要があります。このメソッドは、アクセストークンを発行し、アクセストークン、クライアント、およびパーソナルアクセストークンを取り消すために必要なルートを登録します。Next, you should call the Passport::routes method within the boot method of your App\Providers\AuthServiceProvider. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションのポリシーのマップ
     *
     * @var array
     */
    protected $policies = [
        'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * 全認証/認可サービスの登録
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        if (! $this->app->routesAreCached()) {
            Passport::routes();
        }
    }
}

最後に、アプリケーションのconfig/auth.php設定ファイルで、api認証ガードのdriverオプションをpassportに設定する必要があります。これにより、受信APIリクエストを認証するときにPassportのTokenGuardを使用するようにアプリケーションに指示します。Finally, in your application's config/auth.php configuration file, you should set the driver option of the api authentication guard to passport. This will instruct your application to use Passport's TokenGuard when authenticating incoming API requests:

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

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

クライアントUUIDClient UUIDs

--uuidsオプションを指定してpassport:installコマンドを実行することもできます。このオプションは、PassportのClientモデルの主キー値として整数を自動増分する代わりにUUIDを使用することをPassportに指示します。--uuidsオプションを指定してpassport:installコマンドを実行すると、Passportのデフォルトのマイグレーションを無効にするための追加の手順が表示されます。You may also run the passport:install command with the --uuids option present. This option will instruct Passport that you would like to use UUIDs instead of auto-incrementing integers as the Passport Client model's primary key values. After running the passport:install command with the --uuids option, you will be given additional instructions regarding disabling Passport's default migrations:

php artisan passport:install --uuids

PassportのデプロイDeploying Passport

Passportをアプリケーションのサーバに初めてデプロイするときは、passport:keysコマンドを実行する必要があります。このコマンドは、アクセストークンを生成するためにPassportが必要とする暗号化キーを生成します。生成されたキーは通常、ソース管理しません。When deploying Passport to your application's servers for the first time, you will likely need to run the passport:keys command. This command generates the encryption keys Passport needs in order to generate access tokens. The generated keys are not typically kept in source control:

php artisan passport:keys

必要に応じて、Passportのキーをロードするパスを定義できます。これを実現するには、Passport::loadKeysFromメソッドを使用できます。通常、このメソッドは、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドから呼び出す必要があります。If necessary, you may define the path where Passport's keys should be loaded from. You may use the Passport::loadKeysFrom method to accomplish this. Typically, this method should be called from the boot method of your application's App\Providers\AuthServiceProvider class:

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::loadKeysFrom(__DIR__.'/../secrets/oauth');
}

環境からキーのロードLoading Keys From The Environment

または、vendor:publish Artisanコマンドを使用してPassportの設定ファイルをリソース公開することもできます。Alternatively, you may publish Passport's configuration file using the vendor:publish Artisan command:

php artisan vendor:publish --tag=passport-config

設定ファイルをリソース公開した後、環境変数として定義することにより、アプリケーションの暗号化キーをロードできます。After the configuration file has been published, you may load your application's encryption keys by defining them as environment variables:

PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
<private key here>
-----END RSA PRIVATE KEY-----"

PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
<public key here>
-----END PUBLIC KEY-----"

マイグレーションのカスタマイズMigration Customization

Passportのデフォルトのマイグレーションを使用しない場合は、App\Providers\AppServiceProviderクラスのregisterメソッドでPassport::ignoreMigrationsメソッドを呼び出す必要があります。vendor:publish Artisanコマンドを使用してデフォルトのマイグレーションをエクスポートできます。If you are not going to use Passport's default migrations, you should call the Passport::ignoreMigrations method in the register method of your App\Providers\AppServiceProvider class. You may export the default migrations using the vendor:publish Artisan command:

php artisan vendor:publish --tag=passport-migrations

PassportのアップグレードUpgrading Passport

Passportの新しいメジャーバージョンにアップグレードするときは、アップグレードガイドを注意深く確認することが重要です。When upgrading to a new major version of Passport, it's important that you carefully review the upgrade guide[https://github.com/laravel/passport/blob/master/UPGRADE.md].

設定Configuration

クライアントシークレットハッシュClient Secret Hashing

データベースに保存するときにクライアントのシークレットをハッシュする場合は、App\Providers\AuthServiceProviderクラスのbootメソッドでPassport::hashClientSecretsメソッドを呼び出す必要があります。If you would like your client's secrets to be hashed when stored in your database, you should call the Passport::hashClientSecrets method in the boot method of your App\Providers\AuthServiceProvider class:

use Laravel\Passport\Passport;

Passport::hashClientSecrets();

有効にすると、すべてのクライアントシークレットは、作成した直後のみユーザーへ表示されます。平文テキストのクライアントシークレット値がデータベースに保存されることはないため、シークレットの値が失われた場合にその値を回復することはできません。Once enabled, all of your client secrets will only be displayable to the user immediately after they are created. Since the plain-text client secret value is never stored in the database, it is not possible to recover the secret's value if it is lost.

トークン持続時間Token Lifetimes

デフォルトでは、Passportは1年後に有効期限が切れる長期アクセストークンを発行します。より長い/短いトークン有効期間を設定したい場合は、tokensExpireInrefreshTokensExpireInpersonalAccessTokensExpireInメソッドを使用します。これらのメソッドは、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドで呼び出す必要があります。By default, Passport issues long-lived access tokens that expire after one year. If you would like to configure a longer / shorter token lifetime, you may use the tokensExpireIn, refreshTokensExpireIn, and personalAccessTokensExpireIn methods. These methods should be called from the boot method of your application's App\Providers\AuthServiceProvider class:

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensExpireIn(now()->addDays(15));
    Passport::refreshTokensExpireIn(now()->addDays(30));
    Passport::personalAccessTokensExpireIn(now()->addMonths(6));
}

Note: note Passportのデータベーステーブルのexpires_atカラムは読み取り専用であり、表示のみを目的としています。トークンを発行するとき、Passportは署名および暗号化されたトークン内に有効期限情報を保存します。トークンを無効にする必要がある場合は、取り消す必要があります。{note} The expires_at columns on Passport's database tables are read-only and for display purposes only. When issuing tokens, Passport stores the expiration information within the signed and encrypted tokens. If you need to invalidate a token you should revoke it[#revoking-tokens].

デフォルトモデルのオーバーライドOverriding Default Models

独自のモデルを定義し、対応するPassportモデルを拡張することにより、Passportにより内部的に使用されるモデルを自由に拡張できます。You are free to extend the models used internally by Passport by defining your own model and extending the corresponding Passport model:

use Laravel\Passport\Client as PassportClient;

class Client extends PassportClient
{
    // ...
}

モデルを定義した後、Laravel\Passport\Passportクラスを介してカスタムモデルを使用するようにPassportに指示します。通常、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドでカスタムモデルをPassportへ知らせる必要があります。After defining your model, you may instruct Passport to use your custom model via the Laravel\Passport\Passport class. Typically, you should inform Passport about your custom models in the boot method of your application's App\Providers\AuthServiceProvider class:

use App\Models\Passport\AuthCode;
use App\Models\Passport\Client;
use App\Models\Passport\PersonalAccessClient;
use App\Models\Passport\Token;

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::useTokenModel(Token::class);
    Passport::useClientModel(Client::class);
    Passport::useAuthCodeModel(AuthCode::class);
    Passport::usePersonalAccessClientModel(PersonalAccessClient::class);
}

アクセストークンの発行Issuing Access Tokens

認証コードを介してOAuth2を使用することは、OAuth2を扱う時にほとんどの開発者が精通している方法です。認証コードを使用する場合、クライアントアプリケーションはユーザーをサーバにリダイレクトし、そこでユーザーはクライアントへアクセストークンを発行するリクエストを承認または拒否します。Using OAuth2 via authorization codes is how most developers are familiar with OAuth2. When using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.

クライアント管理Managing Clients

あなたのアプリケーションのAPIと連携する必要のある、アプリケーションを構築しようとしている開発者たちは、最初に「クライアント」を作成することにより、彼らのアプリケーションを登録しなくてはなりません。通常、アプリケーションの名前と、許可のリクエストをユーザーが承認した後に、アプリケーションがリダイレクトされるURLにより、登録情報は構成されます。First, developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URL that your application can redirect to after users approve their request for authorization.

passport:clientコマンドThe passport:client Command

クライアントを作成する一番簡単な方法は、passport:client Artisanコマンドを使うことです。このコマンドは、OAuth2の機能をテストするため、皆さん自身のクライアントを作成する場合に使用できます。clientコマンドを実行すると、Passportはクライアントに関する情報の入力を促し、クライアントIDとシークレットを表示します。The simplest way to create a client is using the passport:client Artisan command. This command may be used to create your own clients for testing your OAuth2 functionality. When you run the client command, Passport will prompt you for more information about your client and will provide you with a client ID and secret:

php artisan passport:client

リダイレクトURLRedirect URLs

クライアントに複数のリダイレクトURLを許可する場合は、passport:clientコマンドでURLの入力を求められたときに、カンマ区切りのリストを使用して指定してください。カンマを含むURLは、URLエンコードする必要があります。If you would like to allow multiple redirect URLs for your client, you may specify them using a comma-delimited list when prompted for the URL by the passport:client command. Any URLs which contain commas should be URL encoded:

http://example.com/callback,http://examplefoo.com/callback

JSON APIJSON API

アプリケーションのユーザーはclientコマンドを利用できないため、Passportはクライアントの作成に使用できるJSON APIを提供します。これにより、クライアントを作成、更新、および削除するためにコントローラを手動でコーディングする手間が省けます。Since your application's users will not be able to utilize the client command, Passport provides a JSON API that you may use to create clients. This saves you the trouble of having to manually code controllers for creating, updating, and deleting clients.

しかし、ユーザーにクライアントを管理してもらうダッシュボードを提供するために、PassportのJSON APIと皆さんのフロントエンドを結合する必要があります。以降から、クライアントを管理するためのAPIエンドポイントをすべて説明します。エンドポイントへのHTTPリクエスト作成をデモンストレートするため利便性を考慮し、Axiosを使用していきましょう。However, you will need to pair Passport's JSON API with your own frontend to provide a dashboard for your users to manage their clients. Below, we'll review all of the API endpoints for managing clients. For convenience, we'll use Axios[https://github.com/axios/axios] to demonstrate making HTTP requests to the endpoints.

JSON APIはwebauthミドルウェアにより保護されています。そのため、みなさん自身のアプリケーションからのみ呼び出せます。外部ソースから呼び出すことはできません。The JSON API is guarded by the web and auth middleware; therefore, it may only be called from your own application. It is not able to be called from an external source.

GET /oauth/clientsGET /oauth/clients

このルートは認証されたユーザーの全クライアントを返します。ユーザーのクライアントの全リストは、主にクライアントを編集、削除する場合に役立ちます。This route returns all of the clients for the authenticated user. This is primarily useful for listing all of the user's clients so that they may edit or delete them:

axios.get('/oauth/clients')
    .then(response => {
        console.log(response.data);
    });

POST /oauth/clientsPOST /oauth/clients

このルートは新クライアントを作成するために使用します。これには2つのデータが必要です。クライアントの名前(name)と、リダイレクト(redirect)のURLです。redirectのURLは許可のリクエストが承認されるか、拒否された後のユーザーのリダイレクト先です。This route is used to create new clients. It requires two pieces of data: the client's name and a redirect URL. The redirect URL is where the user will be redirected after approving or denying a request for authorization.

クライアントを作成すると、クライアントIDとクライアントシークレットが発行されます。これらの値はあなたのアプリケーションへリクエストし、アクセストークンを取得する時に使用されます。クライアント作成ルートは、新しいクライアントインスタンスを返します。When a client is created, it will be issued a client ID and client secret. These values will be used when requesting access tokens from your application. The client creation route will return the new client instance:

const data = {
    name: 'Client Name',
    redirect: 'http://example.com/callback'
};

axios.post('/oauth/clients', data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // レスポンス上のエラーのリスト
    });

PUT /oauth/clients/{client-id}PUT /oauth/clients/{client-id}

このルートはクライアントを更新するために使用します。それには2つのデータが必要です。クライアントのnameredirectのURLです。redirectのURLは許可のリクエストが承認されるか、拒否され後のユーザーのリダイレクト先です。このルートは更新されたクライアントインスタンスを返します。This route is used to update clients. It requires two pieces of data: the client's name and a redirect URL. The redirect URL is where the user will be redirected after approving or denying a request for authorization. The route will return the updated client instance:

const data = {
    name: 'New Client Name',
    redirect: 'http://example.com/callback'
};

axios.put('/oauth/clients/'   clientId, data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // レスポンス上のエラーのリスト
    });

DELETE /oauth/clients/{client-id}DELETE /oauth/clients/{client-id}

このルートはクライアントを削除するために使用します。This route is used to delete clients:

axios.delete('/oauth/clients/'   clientId)
    .then(response => {
        //
    });

トークンのリクエストRequesting Tokens

許可のリダイレクトRedirecting For Authorization

クライアントが作成されると、開発者はクライアントIDとシークレットを使用し、あなたのアプリケーションへ許可コードとアクセストークンをリクエストするでしょう。まず、API利用側アプリケーションは以下のように、あなたのアプリケーションの/oauth/authorizeルートへのリダイレクトリクエストを作成する必要があります。Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's /oauth/authorize route like so:

use Illuminate\Http\Request;
use Illuminate\Support\Str;

Route::get('/redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));

    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'response_type' => 'code',
        'scope' => '',
        'state' => $state,
    ]);

    return redirect('http://passport-app.test/oauth/authorize?'.$query);
});

lightbulb">Tip!! /oauth/authorizeルートは、すでにPassport::routesメソッドが定義づけていることを覚えておいてください。このルートを自分で定義する必要はありません。{tip} Remember, the /oauth/authorize route is already defined by the Passport::routes method. You do not need to manually define this route.

リクエストの承認Approving The Request

許可のリクエストを受け取ると、Passportはユーザーがその許可のリクエストを承認するか、拒絶するかのテンプレートを自動的に表示します。ユーザーが許可した場合、API利用側アプリケーションが指定したredirect_uriへリダイレクトします。redirect_uriは、クライアントを作成した時に指定したredirectのURLと一致する必要があります。When receiving authorization requests, Passport will automatically display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the redirect_uri that was specified by the consuming application. The redirect_uri must match the redirect URL that was specified when the client was created.

承認画面をカスタマイズする場合は、vendor:publish Artisanコマンドを使用してPassportのビューをリソース公開します。公開したビューは、resources/views/vendor/passportディレクトリに配置されます。If you would like to customize the authorization approval screen, you may publish Passport's views using the vendor:publish Artisan command. The published views will be placed in the resources/views/vendor/passport directory:

php artisan vendor:publish --tag=passport-views

ファーストパーティ製クライアントにより認可中のような場合、認可プロンプトをとばしたい場合もあり得ます。Clientモデルを拡張しskipsAuthorizationメソッドを定義することで実現できます。skipsAuthorizationがクライアントは認証済みとしてtrueを返すと、そのユーザーをすぐにredirect_uriへリダイレクトで戻します。Sometimes you may wish to skip the authorization prompt, such as when authorizing a first-party client. You may accomplish this by extending the Client model[#overriding-default-models] and defining a skipsAuthorization method. If skipsAuthorization returns true the client will be approved and the user will be redirected back to the redirect_uri immediately:

<?php

namespace App\Models\Passport;

use Laravel\Passport\Client as BaseClient;

class Client extends BaseClient
{
    /**
     * クライアントが認可プロンプトを飛ばすべきか決める
     *
     * @return bool
     */
    public function skipsAuthorization()
    {
        return $this->firstParty();
    }
}

許可コードからアクセストークンへの変換Converting Authorization Codes To Access Tokens

ユーザーが承認リクエストを承認すると、ユーザーは利用側アプリケーションにリダイレクトされます。利用側はまず、リダイレクトの前に保存した値に対してstateパラメーターを確認する必要があります。状態パラメータが一致する場合、利用側はアプリケーションへPOSTリクエストを発行してアクセストークンをリクエストする必要があります。リクエストには、ユーザーが認証リクエストを承認したときにアプリケーションが発行した認証コードを含める必要があります。If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should first verify the state parameter against the value that was stored prior to the redirect. If the state parameter matches then the consumer should issue a POST request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

Route::get('/callback', function (Request $request) {
    $state = $request->session()->pull('state');

    throw_unless(
        strlen($state) > 0 && $state === $request->state,
        InvalidArgumentException::class
    );

    $response = Http::asForm()->post('http://passport-app.test/oauth/token', [
        'grant_type' => 'authorization_code',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'code' => $request->code,
    ]);

    return $response->json();
});

この/oauth/tokenルートは、access_tokenrefresh_tokenexpires_in属性を含むJSONレスポンスを返します。expires_in属性は、アクセストークンが無効になるまでの秒数を含んでいます。This /oauth/token route will return a JSON response containing access_token, refresh_token, and expires_in attributes. The expires_in attribute contains the number of seconds until the access token expires.

lightbulb">Tip!! /oauth/authorizeルートと同様に、/oauth/tokenルートはPassport::routesメソッドによって定義されます。このルートを手動で定義する必要はありません。{tip} Like the /oauth/authorize route, the /oauth/token route is defined for you by the Passport::routes method. There is no need to manually define this route.

JSON APIJSON API

Passportには、承認済みアクセストークンを管理するためのJSON APIも含んでいます。これを独自のフロントエンドと組み合わせ、アクセストークンを管理するダッシュボードをユーザーへ提供できます。便宜上、AxiosをエンドポイントへのHTTPリクエストを生成するデモンストレーションのため使用しています。JSON APIはwebauthミドルウェアにより保護されているため、自身のアプリケーションからのみ呼び出しできます。Passport also includes a JSON API for managing authorized access tokens. You may pair this with your own frontend to offer your users a dashboard for managing access tokens. For convenience, we'll use Axios[https://github.com/mzabriskie/axios] to demonstrate making HTTP requests to the endpoints. The JSON API is guarded by the web and auth middleware; therefore, it may only be called from your own application.

GET /oauth/tokensGET /oauth/tokens

このルートは、認証されたユーザーが作成した、承認済みアクセストークンをすべて返します。これは主に取り消すトークンを選んでもらうため、ユーザーの全トークンを一覧リスト表示するのに便利です。This route returns all of the authorized access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they can revoke them:

axios.get('/oauth/tokens')
    .then(response => {
        console.log(response.data);
    });

DELETE /oauth/tokens/{token-id}DELETE /oauth/tokens/{token-id}

このルートは、認証済みアクセストークンと関連するリフレッシュトークンを取り消すために使います。This route may be used to revoke authorized access tokens and their related refresh tokens:

axios.delete('/oauth/tokens/'   tokenId);

トークンのリフレッシュRefreshing Tokens

アプリケーションが短期間のアクセストークンを発行する場合、ユーザーはアクセストークンが発行されたときに提供された更新トークンを利用して、アクセストークンを更新する必要があります。If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued:

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
    'grant_type' => 'refresh_token',
    'refresh_token' => 'the-refresh-token',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'scope' => '',
]);

return $response->json();

この/oauth/tokenルートは、access_tokenrefresh_tokenexpires_in属性を含むJSONレスポンスを返します。expires_in属性は、アクセストークンが無効になるまでの秒数を含んでいます。This /oauth/token route will return a JSON response containing access_token, refresh_token, and expires_in attributes. The expires_in attribute contains the number of seconds until the access token expires.

トークンの取り消しRevoking Tokens

Laravel\Passport\TokenRepositoryrevokeAccessTokenメソッドを使用してトークンを取り消すことができます。Laravel\Passport\RefreshTokenRepositoryrevokeRefreshTokensByAccessTokenIdメソッドを使用して、トークンの更新トークンを取り消すことができます。これらのクラスは、Laravelのサービスコンテナを使用して解決できます。You may revoke a token by using the revokeAccessToken method on the Laravel\Passport\TokenRepository. You may revoke a token's refresh tokens using the revokeRefreshTokensByAccessTokenId method on the Laravel\Passport\RefreshTokenRepository. These classes may be resolved using Laravel's service container[/docs/{{version}}/container]:

use Laravel\Passport\TokenRepository;
use Laravel\Passport\RefreshTokenRepository;

$tokenRepository = app(TokenRepository::class);
$refreshTokenRepository = app(RefreshTokenRepository::class);

// アクセストークンの取り消し
$tokenRepository->revokeAccessToken($tokenId);

// そのトークンのリフレッシュトークンを全て取り消し
$refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId);

トークンの破棄Purging Tokens

トークンが取り消されたり期限切れになったりした場合は、データベースからトークンを削除することを推奨します。Passportに含まれているpassport:purge Artisanコマンドでこれを実行できます。When tokens have been revoked or expired, you might want to purge them from the database. Passport's included passport:purge Artisan command can do this for you:

# 無効・期限切れのトークンと認可コードを破棄する
php artisan passport:purge

# 無効なトークンと認可コードのみ破棄する
php artisan passport:purge --revoked

# 期限切れのトークンと認可コードのみ破棄する
php artisan passport:purge --expired

また、アプリケーションのApp\Console\Kernelクラスでジョブの実行スケジュールを設定して、スケジュールに従ってトークンを自動的に整理することもできます。You may also configure a scheduled job[/docs/{{version}}/scheduling] in your application's App\Console\Kernel class to automatically prune your tokens on a schedule:

/**
 * アプリケーションのコマンドスケジュール定義
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('passport:purge')->hourly();
}

PKCEを使った認可コードグラントAuthorization Code Grant with PKCE

"Proof Key for Code Exchange" (PKCE)を使用する認可コードグラントは、シングルページアプリケーションやネイティブアプリケーションが、APIへアクセスするための安全な認証方法です。このグラントはクライアントの秘密コードを十分な機密を保ち保存できないか、もしくは認可コード横取り攻撃の危険を軽減する必要がある場合に、必ず使用すべきです。アクセストークンのために認可コードを交換するときに、クライアントの秘密コードを「コードベリファイヤ(code verifier)」と「コードチャレンジ(code challenge)」のコンピネーションに置き換えます。The Authorization Code grant with "Proof Key for Code Exchange" (PKCE) is a secure way to authenticate single page applications or native applications to access your API. This grant should be used when you can't guarantee that the client secret will be stored confidentially or in order to mitigate the threat of having the authorization code intercepted by an attacker. A combination of a "code verifier" and a "code challenge" replaces the client secret when exchanging the authorization code for an access token.

クライアント生成Creating The Client

アプリケーションがPKCEでの認証コードグラントを介してトークンを発行する前に、PKCE対応のクライアントを作成する必要があります。これは、passport:client Artisanコマンドと--publicオプションを使用して行えます。Before your application can issue tokens via the authorization code grant with PKCE, you will need to create a PKCE-enabled client. You may do this using the passport:client Artisan command with the --public option:

php artisan passport:client --public

トークンのリクエストRequesting Tokens

コードベリファイヤとコードチャレンジCode Verifier & Code Challenge

この認可グラントではクライアント秘密コードが提供されないため、開発者はトークンを要求するためにコードベリファイヤとコードチャレンジのコンビネーションを生成する必要があります。As this authorization grant does not provide a client secret, developers will need to generate a combination of a code verifier and a code challenge in order to request a token.

コードベリファイアは、RFC 7636 仕様で定義されているように、文字、数字、"-"".""_""~"文字を含む43文字から128文字のランダムな文字列でなければなりません。The code verifier should be a random string of between 43 and 128 characters containing letters, numbers, and "-", ".", "_", "~" characters, as defined in the RFC 7636 specification[https://tools.ietf.org/html/rfc7636].

コードチャレンジはURL/ファイルネームセーフな文字をBase64エンコードしたものである必要があります。文字列終端の'='文字を削除し、ラインブレイクやホワイトスペースを含まず、その他はそのままにします。The code challenge should be a Base64 encoded string with URL and filename-safe characters. The trailing '=' characters should be removed and no line breaks, whitespace, or other additional characters should be present.

$encoded = base64_encode(hash('sha256', $code_verifier, true));

$codeChallenge = strtr(rtrim($encoded, '='), ' /', '-_');

許可のリダイレクトRedirecting For Authorization

クライアントが生成できたら、アプリケーションから認可コードとアクセストークンをリクエストするために、クライアントIDと生成したコードベリファイヤ、コードチャレンジを使用します。最初に、認可要求側のアプリケーションは、あなたのアプリケーションの/oauth/authorizeルートへのリダイレクトリクエストを生成する必要があります。Once a client has been created, you may use the client ID and the generated code verifier and code challenge to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's /oauth/authorize route:

use Illuminate\Http\Request;
use Illuminate\Support\Str;

Route::get('/redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));

    $request->session()->put(
        'code_verifier', $code_verifier = Str::random(128)
    );

    $codeChallenge = strtr(rtrim(
        base64_encode(hash('sha256', $code_verifier, true))
    , '='), ' /', '-_');

    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'response_type' => 'code',
        'scope' => '',
        'state' => $state,
        'code_challenge' => $codeChallenge,
        'code_challenge_method' => 'S256',
    ]);

    return redirect('http://passport-app.test/oauth/authorize?'.$query);
});

許可コードからアクセストークンへの変換Converting Authorization Codes To Access Tokens

ユーザーが認可リクエストを承認すると、認可要求側のアプリケーションへリダイレクで戻されます。認可要求側では認可コードグラントの規約に従い、リダイレクトの前に保存しておいた値と、stateパラメータを検証する必要があります。If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should verify the state parameter against the value that was stored prior to the redirect, as in the standard Authorization Code Grant.

stateパラメータが一致したら、要求側はアクセストークンをリクエストするために、あなたのアプリケーションへPOSTリクエストを発行する必要があります。そのリクエストは最初に生成したコードベリファイヤと同時に、ユーザーが認可リクエストを承認したときにあなたのアプリケーションが発行した認可コードを持っている必要があります。If the state parameter matches, the consumer should issue a POST request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request along with the originally generated code verifier:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

Route::get('/callback', function (Request $request) {
    $state = $request->session()->pull('state');

    $codeVerifier = $request->session()->pull('code_verifier');

    throw_unless(
        strlen($state) > 0 && $state === $request->state,
        InvalidArgumentException::class
    );

    $response = Http::asForm()->post('http://passport-app.test/oauth/token', [
        'grant_type' => 'authorization_code',
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'code_verifier' => $codeVerifier,
        'code' => $request->code,
    ]);

    return $response->json();
});

パスワードグラントのトークンPassword Grant Tokens

Note: note パスワードグラントトークンの使用は、現在推奨していません。代わりに、OAuth2サーバが現在推奨しているグラントタイプ を選択する必要があります。{note} We no longer recommend using password grant tokens. Instead, you should choose a grant type that is currently recommended by OAuth2 Server[https://oauth2.thephpleague.com/authorization-server/which-grant/].

OAuth2パスワードグラントにより、モバイルアプリケーションなどの他のファーストパーティクライアントは、電子メールアドレス/ユーザー名とパスワードを使用してアクセストークンを取得できます。これにより、ユーザーがOAuth2認証コードのリダイレクトフロー全体を実行しなくても、ファーストパーティクライアントにアクセストークンを安全に発行できます。The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an email address / username and password. This allows you to issue access tokens securely to your first-party clients without requiring your users to go through the entire OAuth2 authorization code redirect flow.

パスワードグラントクライアントの作成Creating A Password Grant Client

アプリケーションがパスワードグラントを介してトークンを発行する前に、パスワードグラントクライアントを作成する必要があります。これは、--passwordオプションを指定したpassport:client Artisanコマンドを使用して行えます。すでにpassport:installコマンドを実行している場合は、次のコマンドを実行する必要はありません:Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the passport:client Artisan command with the --password option. If you have already run the passport:install command, you do not need to run this command:

php artisan passport:client --password

トークンのリクエストRequesting Tokens

パスワードグラントクライアントを作成したら、ユーザーのメールアドレスとパスワードを指定し、/oauth/tokenルートへPOSTリクエストを発行することで、アクセストークンをリクエストできます。このルートは、Passport::routesメソッドが登録しているため、自分で定義する必要がないことを覚えておきましょう。リクエストに成功すると、サーバからaccess_tokenrefresh_tokenのJSONレスポンスを受け取ります。Once you have created a password grant client, you may request an access token by issuing a POST request to the /oauth/token route with the user's email address and password. Remember, this route is already registered by the Passport::routes method so there is no need to define it manually. If the request is successful, you will receive an access_token and refresh_token in the JSON response from the server:

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => 'taylor@laravel.com',
    'password' => 'my-password',
    'scope' => '',
]);

return $response->json();

lightbulb">Tip!! アクセストークンはデフォルトで、長期間有効であることを記憶しておきましょう。ただし、必要であれば自由に、アクセストークンの最長持続時間を設定できます。{tip} Remember, access tokens are long-lived by default. However, you are free to configure your maximum access token lifetime[#configuration] if needed.

全スコープの要求Requesting All Scopes

パスワードグラント、またはクライアント認証情報グラントを使用時は、あなたのアプリケーションでサポートする全スコープを許可するトークンを発行したいと考えるかと思います。*スコープをリクエストすれば可能です。*スコープをリクエストすると、そのトークンインスタンスのcanメソッドは、いつもtrueを返します。このスコープはpasswordclient_credentialsグラントを使って発行されたトークのみに割り付けるのが良いでしょう。When using the password grant or client credentials grant, you may wish to authorize the token for all of the scopes supported by your application. You can do this by requesting the * scope. If you request the * scope, the can method on the token instance will always return true. This scope may only be assigned to a token that is issued using the password or client_credentials grant:

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => 'taylor@laravel.com',
    'password' => 'my-password',
    'scope' => '*',
]);

ユーザープロバイダのカスタマイズCustomizing The User Provider

アプリケーションが複数の認証ユーザープロバイダを使用している場合は、artisan passport:client --passwordコマンドを介してクライアントを作成する時に、--providerオプションを指定することで、パスワードグラントクライアントが使用するユーザープロバイダを指定できます。指定するプロバイダ名は、アプリケーションのconfig/auth.php設定ファイルで定義している有効なプロバイダと一致する必要があります。次に、ミドルウェアを使用してルートを保護して、ガードの指定するプロバイダのユーザーのみが許可されるようにすることができます。If your application uses more than one authentication user provider[/docs/{{version}}/authentication#introduction], you may specify which user provider the password grant client uses by providing a --provider option when creating the client via the artisan passport:client --password command. The given provider name should match a valid provider defined in your application's config/auth.php configuration file. You can then protect your route using middleware[#via-middleware] to ensure that only users from the guard's specified provider are authorized.

ユーザー名フィールドのカスタマイズCustomizing The Username Field

パスワードグラントを使用して認証する場合、Passportは認証可能なモデルのemail属性を「ユーザー名」として使用します。ただし、モデルでfindForPassportメソッドを定義することにより、この動作をカスタマイズできます。When authenticating using the password grant, Passport will use the email attribute of your authenticatable model as the "username". However, you may customize this behavior by defining a findForPassport method on your model:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * 指定されたユーザー名のユーザーインスタンスを見つける
     *
     * @param  string  $username
     * @return \App\Models\User
     */
    public function findForPassport($username)
    {
        return $this->where('username', $username)->first();
    }
}

パスワードバリデーションのカスタマイズCustomizing The Password Validation

パスワードガードを使用して認証している場合、Passportは指定されたパスワードを確認するためにモデルのpassword属性を使用します。もし、password属性を持っていないか、パスワードのバリデーションロジックをカスタマイズしたい場合は、モデルのvalidateForPassportPasswordGrantメソッドを定義してください。When authenticating using the password grant, Passport will use the password attribute of your model to validate the given password. If your model does not have a password attribute or you wish to customize the password validation logic, you can define a validateForPassportPasswordGrant method on your model:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * Passportパスワードグラントのために、ユーザーのパスワードをバリデート
     *
     * @param  string  $password
     * @return bool
     */
    public function validateForPassportPasswordGrant($password)
    {
        return Hash::check($password, $this->password);
    }
}

暗黙のグラントトークンImplicit Grant Tokens

Note: note 暗黙的のグラント・トークンの使用は、現在推奨していません。代わりに、OAuth2サーバが現在推奨しているグラントタイプ を選択する必要があります。{note} We no longer recommend using implicit grant tokens. Instead, you should choose a grant type that is currently recommended by OAuth2 Server[https://oauth2.thephpleague.com/authorization-server/which-grant/].

暗黙的なグラントは、認証コードグラントに似ています。ただし、トークンは認証コードを交換せずにクライアントへ返します。このグラントは、クライアントの利用資格情報を安全に保存できないJavaScriptまたはモバイルアプリケーションで最も一般的に使用します。このグラントを有効にするには、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドでenableImplicitGrantメソッドを呼び出します。The implicit grant is similar to the authorization code grant; however, the token is returned to the client without exchanging an authorization code. This grant is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored. To enable the grant, call the enableImplicitGrant method in the boot method of your application's App\Providers\AuthServiceProvider class:

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::enableImplicitGrant();
}

暗黙グラントが有効になると、開発者はクライアントIDを使用してアプリケーションにアクセストークンをリクエストできます。利用側アプリケーションは、次のようにアプリケーションの/oauth/authorizeルートにリダイレクトリクエストを行う必要があります。Once the grant has been enabled, developers may use their client ID to request an access token from your application. The consuming application should make a redirect request to your application's /oauth/authorize route like so:

use Illuminate\Http\Request;

Route::get('/redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));

    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'response_type' => 'token',
        'scope' => '',
        'state' => $state,
    ]);

    return redirect('http://passport-app.test/oauth/authorize?'.$query);
});

lightbulb">Tip!! /oauth/authorizeルートは、すでにPassport::routesメソッドが定義づけていることを覚えておいてください。このルートを自分で定義する必要はありません。{tip} Remember, the /oauth/authorize route is already defined by the Passport::routes method. You do not need to manually define this route.

クライアント認証情報グラントトークンClient Credentials Grant Tokens

クライアント認証情報グラントはマシンーマシン間の認証に最適です。たとえば、APIによりメンテナンスタスクを実行する、定期実行ジョブに使用できます。The client credentials grant is suitable for machine-to-machine authentication. For example, you might use this grant in a scheduled job which is performing maintenance tasks over an API.

アプリケーションがクライアント利用資格情報グラントを介してトークンを発行する前に、クライアント利用資格情報グラントクライアントを作成する必要があります。これは、passport:client Artisanコマンドの--clientオプションを使用して行うことができます。Before your application can issue tokens via the client credentials grant, you will need to create a client credentials grant client. You may do this using the --client option of the passport:client Artisan command:

php artisan passport:client --client

次に、このグラントタイプを使用するために、app/Http/Kernel.phpファイルの$routeMiddlewareへ、CheckClientCredentialsミドルウェアを追加する必要があります。Next, to use this grant type, you need to add the CheckClientCredentials middleware to the $routeMiddleware property of your app/Http/Kernel.php file:

use Laravel\Passport\Http\Middleware\CheckClientCredentials;

protected $routeMiddleware = [
    'client' => CheckClientCredentials::class,
];

それから、ルートへこのミドルウェアを指定します。Then, attach the middleware to a route:

Route::get('/orders', function (Request $request) {
    ...
})->middleware('client');

ルートへのアクセスを特定のスコープに制限するには、clientミドルウェアをルートに接続するときに、必要なスコープのコンマ区切りのリストを指定できます。To restrict access to the route to specific scopes, you may provide a comma-delimited list of the required scopes when attaching the client middleware to the route:

Route::get('/orders', function (Request $request) {
    ...
})->middleware('client:check-status,your-scope');

トークンの取得Retrieving Tokens

このグラントタイプを使用してトークンを取得するには、oauth/tokenエンドポイントにリクエストを送信します。To retrieve a token using this grant type, make a request to the oauth/token endpoint:

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
    'grant_type' => 'client_credentials',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'scope' => 'your-scope',
]);

return $response->json()['access_token'];

パーソナルアクセストークンPersonal Access Tokens

ときどき、あなたのユーザーが典型的なコードリダイレクションフローに従うのではなく、自分たち自身でアクセストークンを発行したがることもあるでしょう。あなたのアプリケーションのUIを通じて、ユーザー自身のトークンを発行を許可することにより、あなたのAPIをユーザーに経験してもらう事ができますし、全般的なアクセストークン発行するシンプルなアプローチとしても役立つでしょう。Sometimes, your users may want to issue access tokens to themselves without going through the typical authorization code redirect flow. Allowing users to issue tokens to themselves via your application's UI can be useful for allowing users to experiment with your API or may serve as a simpler approach to issuing access tokens in general.

lightbulb">Tip!! あなたのアプリケーションが主にPassportを使用して個人アクセストークンを発行している場合、APIアクセストークンを発行するためのLaravelの軽量なファーストパーティーライブラリ、Laravel Sanctumの使用を検討してください。{tip} If your application is primarily using Passport to issue personal access tokens, consider using Laravel Sanctum[/docs/{{version}}/sanctum], Laravel's light-weight first-party library for issuing API access tokens.

パーソナルアクセスクライアントの作成Creating A Personal Access Client

アプリケーションがパーソナルアクセストークンを発行する前に、パーソナルアクセスクライアントを作成する必要があります。これを行うには、--personalオプションを指定してpassport:client Artisanコマンドを実行します。すでにpassport:installコマンドを実行している場合は、次のコマンドを実行する必要はありません。Before your application can issue personal access tokens, you will need to create a personal access client. You may do this by executing the passport:client Artisan command with the --personal option. If you have already run the passport:install command, you do not need to run this command:

php artisan passport:client --personal

パーソナルアクセスクライアントを制作したら、クライアントIDと平文シークレット値をアプリケーションの.envファイルに設定してください。After creating your personal access client, place the client's ID and plain-text secret value in your application's .env file:

PASSPORT_PERSONAL_ACCESS_CLIENT_ID="client-id-value"
PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET="unhashed-client-secret-value"

パーソナルアクセストークンの管理Managing Personal Access Tokens

パーソナルアクセスクライアントを作成したら、App\Models\UserモデルインスタンスでcreateTokenメソッドを使用して特定のユーザーにトークンを発行できます。createTokenメソッドは、最初の引数にトークン名、2番目の引数にオプションのスコープの配列を取ります。Once you have created a personal access client, you may issue tokens for a given user using the createToken method on the App\Models\User model instance. The createToken method accepts the name of the token as its first argument and an optional array of scopes[#token-scopes] as its second argument:

use App\Models\User;

$user = User::find(1);

// スコープ無しのトークンを作成する
$token = $user->createToken('Token Name')->accessToken;

// スコープ付きのトークンを作成する
$token = $user->createToken('My Token', ['place-orders'])->accessToken;

JSON APIJSON API

Passportにはパーソナルアクセストークンを管理するためのJSON APIも含まれています。ユーザーにパーソナルアクセストークンを管理してもらうダッシュボードを提供するため、APIと皆さんのフロントエンドを結びつける必要があるでしょう。以降から、パーソナルアクセストークンを管理するためのAPIエンドポイントをすべて説明します。利便性を考慮し、エンドポイントへのHTTPリクエスト作成をデモンストレートするために、Axiosを使用していきましょう。Passport also includes a JSON API for managing personal access tokens. You may pair this with your own frontend to offer your users a dashboard for managing personal access tokens. Below, we'll review all of the API endpoints for managing personal access tokens. For convenience, we'll use Axios[https://github.com/mzabriskie/axios] to demonstrate making HTTP requests to the endpoints.

JSON APIはwebauthミドルウェアにより保護されています。そのため、みなさん自身のアプリケーションからのみ呼び出せます。外部ソースから呼び出すことはできません。The JSON API is guarded by the web and auth middleware; therefore, it may only be called from your own application. It is not able to be called from an external source.

GET /oauth/scopesGET /oauth/scopes

このルートはあなたのアプリケーションで定義した、全スコープを返します。このルートを使い、ユーザーがパーソナルアクセストークンに割り付けたスコープをリストできます。This route returns all of the scopes[#token-scopes] defined for your application. You may use this route to list the scopes a user may assign to a personal access token:

axios.get('/oauth/scopes')
    .then(response => {
        console.log(response.data);
    });

GET /oauth/personal-access-tokensGET /oauth/personal-access-tokens

このルートは認証中のユーザーが作成したパーソナルアクセストークンをすべて返します。ユーザーがトークンの編集や取り消しを行うため、全トークンをリストするために主に使われます。This route returns all of the personal access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they may edit or revoke them:

axios.get('/oauth/personal-access-tokens')
    .then(response => {
        console.log(response.data);
    });

POST /oauth/personal-access-tokensPOST /oauth/personal-access-tokens

このルートは新しいパーソナルアクセストークンを作成します。トークンの名前(name)と、トークンに割り付けるスコープ(scope)の、2つのデータが必要です。This route creates new personal access tokens. It requires two pieces of data: the token's name and the scopes that should be assigned to the token:

const data = {
    name: 'Token Name',
    scopes: []
};

axios.post('/oauth/personal-access-tokens', data)
    .then(response => {
        console.log(response.data.accessToken);
    })
    .catch (response => {
        // レスポンス上のエラーのリスト
    });

DELETE /oauth/personal-access-tokens/{token-id}DELETE /oauth/personal-access-tokens/{token-id}

このルートはパーソナルアクセストークンを取り消すために使用します。This route may be used to revoke personal access tokens:

axios.delete('/oauth/personal-access-tokens/'   tokenId);

ルート保護Protecting Routes

ミドルウェアによる保護Via Middleware

Passportは、受信リクエストのアクセストークンを検証する認証グラントを用意しています。passportドライバを使用するようにapiガードを設定したら、有効なアクセストークンを必要とするルートでauth:apiミドルウェアを指定するだけで済みます。Passport includes an authentication guard[/docs/{{version}}/authentication#adding-custom-guards] that will validate access tokens on incoming requests. Once you have configured the api guard to use the passport driver, you only need to specify the auth:api middleware on any routes that should require a valid access token:

Route::get('/user', function () {
    //
})->middleware('auth:api');

Note: note クライアント認証情報グラントを使用している場合、auth:apiミドルウェアではなく、clientミドルウェアでルートを保護する必要があります。{note} If you are using the client credentials grant[#client-credentials-grant-tokens], you should use the client middleware[#client-credentials-grant-tokens] to protect your routes instead of the auth:api middleware.

複数認証ガードMultiple Authentication Guards

アプリケーションの認証でたぶんまったく異なるEloquentモデルを使用する、別々のタイプのユーザーを認証する場合、それぞれのユーザープロバイダタイプごとにガード設定を定義する必用があるでしょう。これにより特定ユーザープロバイダ向けのリクエストを保護できます。例としてconfig/auth.php設定ファイルで以下のようなガード設定を行っているとしましょう。If your application authenticates different types of users that perhaps use entirely different Eloquent models, you will likely need to define a guard configuration for each user provider type in your application. This allows you to protect requests intended for specific user providers. For example, given the following guard configuration the config/auth.php configuration file:

'api' => [
    'driver' => 'passport',
    'provider' => 'users',
],

'api-customers' => [
    'driver' => 'passport',
    'provider' => 'customers',
],

以下のルートは受信リクエストを認証するためcustomersユーザープロバイダを使用するapi-customersガードを使用します。The following route will utilize the api-customers guard, which uses the customers user provider, to authenticate incoming requests:

Route::get('/customer', function () {
    //
})->middleware('auth:api-customers');

lightbulb">Tip!! Passportを使用する複数ユーザープロバイダ利用の詳細は、パスワードグラントのドキュメントを調べてください。{tip} For more information on using multiple user providers with Passport, please consult the password grant documentation[#customizing-the-user-provider].

アクセストークンの受け渡しPassing The Access Token

Passportにより保護されているルートを呼び出す場合、あなたのアプリケーションのAPI利用者は、リクエストのAuthorizationヘッダとして、アクセストークンをBearerトークンとして指定する必要があります。Guzzle HTTPライブラリを使う場合を例として示します。When calling routes that are protected by Passport, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request. For example, when using the Guzzle HTTP library:

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
])->get('https://passport-app.test/api/user');

return $response->json();

トークンのスコープToken Scopes

スコープは、あるアカウントにアクセスする許可がリクエストされたとき、あなたのAPIクライアントに限定された一連の許可をリクエストできるようにします。たとえば、eコマースアプリケーションを構築している場合、全API利用者へ発注する許可を与える必要はないでしょう。代わりに、利用者へ注文の発送状況にアクセスできる許可を与えれば十分です。言い換えれば、スコープはアプリケーションユーザーに対し、彼らの代理としてのサードパーティアプリケーションが実行できるアクションを制限できるようにします。Scopes allow your API clients to request a specific set of permissions when requesting authorization to access an account. For example, if you are building an e-commerce application, not all API consumers will need the ability to place orders. Instead, you may allow the consumers to only request authorization to access order shipment statuses. In other words, scopes allow your application's users to limit the actions a third-party application can perform on their behalf.

スコープの定義Defining Scopes

APIのスコープは、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドのPassport::tokensCanメソッドを使用して定義できます。tokensCanメソッドは、スコープ名とスコープの説明の配列を引数に取ります。スコープの説明は任意で、承認画面でユーザーに表示されます。You may define your API's scopes using the Passport::tokensCan method in the boot method of your application's App\Providers\AuthServiceProvider class. The tokensCan method accepts an array of scope names and scope descriptions. The scope description may be anything you wish and will be displayed to users on the authorization approval screen:

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensCan([
        'place-orders' => 'Place orders',
        'check-status' => 'Check order status',
    ]);
}

デフォルトスコープDefault Scope

クライアントが特定のスコープをリクエストしない場合は、setDefaultScopeメソッドを使用して、デフォルトのスコープをトークンへアタッチするようにPassportサーバを設定できます。通常、このメソッドは、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドから呼び出す必要があります。If a client does not request any specific scopes, you may configure your Passport server to attach default scope(s) to the token using the setDefaultScope method. Typically, you should call this method from the boot method of your application's App\Providers\AuthServiceProvider class:

use Laravel\Passport\Passport;

Passport::tokensCan([
    'place-orders' => 'Place orders',
    'check-status' => 'Check order status',
]);

Passport::setDefaultScope([
    'check-status',
    'place-orders',
]);

トークンへのスコープ割り付けAssigning Scopes To Tokens

許可コードのリクエスト時When Requesting Authorization Codes

許可コードグラントを用い、アクセストークンをリクエストする際、利用者はscopeクエリ文字列パラメータとして、希望するスコープを指定する必要があります。scopeパラメータはスコープを空白で区切ったリストです。When requesting an access token using the authorization code grant, consumers should specify their desired scopes as the scope query string parameter. The scope parameter should be a space-delimited list of scopes:

Route::get('/redirect', function () {
    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://example.com/callback',
        'response_type' => 'code',
        'scope' => 'place-orders check-status',
    ]);

    return redirect('http://passport-app.test/oauth/authorize?'.$query);
});

パーソナルアクセストークン発行時When Issuing Personal Access Tokens

App\Models\UserモデルのcreateTokenメソッドを使用してパーソナルアクセストークンを発行している場合は、メソッドの2番目の引数に目的のスコープの配列を渡すことができます。If you are issuing personal access tokens using the App\Models\User model's createToken method, you may pass the array of desired scopes as the second argument to the method:

$token = $user->createToken('My Token', ['place-orders'])->accessToken;

スコープのチェックChecking Scopes

Passportには、指定されたスコープが許可されているトークンにより、送信されたリクエストが認証されているかを確認するために使用できる、2つのミドルウエアが用意されています。これを使用するには、app/Http/Kernel.phpファイルの$routeMiddlewareプロパティへ、以下のミドルウェアを追加してください。Passport includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. To get started, add the following middleware to the $routeMiddleware property of your app/Http/Kernel.php file:

'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

全スコープの確認Check For All Scopes

scopesミドルウェアをルートに割り当てて、受信リクエストのアクセストークンがリストするスコープをすべて持っていることを確認できます。The scopes middleware may be assigned to a route to verify that the incoming request's access token has all of the listed scopes:

Route::get('/orders', function () {
    // アクセストークンは"check-status"と"place-orders"、両スコープを持っている
})->middleware(['auth:api', 'scopes:check-status,place-orders']);

一部のスコープの確認Check For Any Scopes

scopeミドルウエアは、リストしたスコープのうち、最低1つを送信されてきたリクエストのアクセストークンが持っていることを確認するため、ルートへ指定します。The scope middleware may be assigned to a route to verify that the incoming request's access token has at least one of the listed scopes:

Route::get('/orders', function () {
    // アクセストークンは、"check-status"か"place-orders"、どちらかのスコープを持っている
})->middleware(['auth:api', 'scope:check-status,place-orders']);

トークンインスタンスでのスコープチェックChecking Scopes On A Token Instance

アクセストークンの認証済みリクエストがアプリケーションに入力された後でも、認証済みのApp\Models\UserインスタンスでtokenCanメソッドを使用して、トークンに特定のスコープがあるかどうかを確認できます。Once an access token authenticated request has entered your application, you may still check if the token has a given scope using the tokenCan method on the authenticated App\Models\User instance:

use Illuminate\Http\Request;

Route::get('/orders', function (Request $request) {
    if ($request->user()->tokenCan('place-orders')) {
        //
    }
});

その他のスコープメソッドAdditional Scope Methods

scopeIdsメソッドは定義済みの全ID/名前の配列を返します。The scopeIds method will return an array of all defined IDs / names:

use Laravel\Passport\Passport;

Passport::scopeIds();

scopesメソッドは定義済みの全スコープをLaravel\Passport\Scopeのインスタンスの配列として返します。The scopes method will return an array of all defined scopes as instances of Laravel\Passport\Scope:

Passport::scopes();

scopesForメソッドは、指定したID/名前に一致するLaravel\Passport\Scopeインスタンスの配列を返します。The scopesFor method will return an array of Laravel\Passport\Scope instances matching the given IDs / names:

Passport::scopesFor(['place-orders', 'check-status']);

指定したスコープが定義済みであるかを判定するには、hasScopeメソッドを使います。You may determine if a given scope has been defined using the hasScope method:

Passport::hasScope('place-orders');

APIをJavaScriptで利用Consuming Your API With JavaScript

API構築時にJavaScriptアプリケーションから、自分のAPIを利用できたらとても便利です。このAPI開発のアプローチにより、世界中で共有されるのと同一のAPIを自身のアプリケーションで使用できるようになります。自分のWebアプリケーションやモバイルアプリケーション、サードパーティアプリケーション、そしてさまざまなパッケージマネージャ上で公開するSDKにより、同じAPIが使用されます。When building an API, it can be extremely useful to be able to consume your own API from your JavaScript application. This approach to API development allows your own application to consume the same API that you are sharing with the world. The same API may be consumed by your web application, mobile applications, third-party applications, and any SDKs that you may publish on various package managers.

通常、皆さんのAPIをJavaScriptアプリケーションから使用しようとするなら、アプリケーションに対しアクセストークンを自分で送り、それを毎回リクエストするたび、一緒にアプリケーションへ渡す必要があります。しかし、Passportにはこれを皆さんに変わって処理するミドルウェアが用意してあります。必要なのはapp/Http/Kernel.phpファイル中の、webミドルウェアグループに対し、CreateFreshApiTokenミドルウェアを追加することだけです。Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Passport includes a middleware that can handle this for you. All you need to do is add the CreateFreshApiToken middleware to your web middleware group in your app/Http/Kernel.php file:

'web' => [
    // 他のミドルウェア…
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

Note: note ミドルウェアの指定の中で、CreateFreshApiTokenミドルウェアは確実に最後へリストしてください。{note} You should ensure that the CreateFreshApiToken middleware is the last middleware listed in your middleware stack.

このミドルウェアは、送信レスポンスにlaravel_tokenクッキーを添付します。このクッキーには、PassportがJavaScriptアプリケーションからのAPIリクエストを認証するために使用する暗号化されたJWTが含まれています。JWTの有効期間は、session.lifetime設定値と同じです。これで、ブラウザは後続のすべてのリクエストでクッキーを自動的に送信するため、アクセストークンを明示的に渡さなくても、アプリケーションのAPIにリクエストを送信できます。This middleware will attach a laravel_token cookie to your outgoing responses. This cookie contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application. The JWT has a lifetime equal to your session.lifetime configuration value. Now, since the browser will automatically send the cookie with all subsequent requests, you may make requests to your application's API without explicitly passing an access token:

axios.get('/api/user')
    .then(response => {
        console.log(response.data);
    });

クッキー名のカスタマイズCustomizing The Cookie Name

必要に応じて、Passport::cookieメソッドを使用してlaravel_tokenクッキーの名前をカスタマイズできます。通常、このメソッドは、アプリケーションのApp\Providers\AuthServiceProviderクラスのbootメソッドから呼び出す必要があります。If needed, you can customize the laravel_token cookie's name using the Passport::cookie method. Typically, this method should be called from the boot method of your application's App\Providers\AuthServiceProvider class:

/**
 * 全認証/認可サービスの登録
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::cookie('custom_name');
}

CSRF保護CSRF Protection

この認証方法を使用する場合、リクエストのヘッダに有効なCSRFトークンを確実に含める必要があります。デフォルトのLaravel JavaScriptスカフォールドはAxiosインスタンスを含み、同一オリジンリクエスト上にX-XSRF-TOKENヘッダを送るために、暗号化されたXSRF-TOKENクッキーを自動的に使用します。When using this method of authentication, you will need to ensure a valid CSRF token header is included in your requests. The default Laravel JavaScript scaffolding includes an Axios instance, which will automatically use the encrypted XSRF-TOKEN cookie value to send an X-XSRF-TOKEN header on same-origin requests.

lightbulb">Tip!! X-XSRF-TOKENの代わりにX-CSRF-TOKENヘッダを送る方法を取る場合は、csrf_token()により提供される復元したトークンを使用する必要があります。{tip} If you choose to send the X-CSRF-TOKEN header instead of X-XSRF-TOKEN, you will need to use the unencrypted token provided by csrf_token().

イベントEvents

Passportは、アクセストークンと更新トークンを発行するときにイベントを発行します。これらのイベントを使用して、データベース内の他のアクセストークンを整理または取り消すことができます。必要に応じて、アプリケーションのApp\Providers\EventServiceProviderクラスでこうしたイベントへリスナを指定できます。Passport raises events when issuing access tokens and refresh tokens. You may use these events to prune or revoke other access tokens in your database. If you would like, you may attach listeners to these events in your application's App\Providers\EventServiceProvider class:

/**
 * アプリケーションのイベントリスナマッピング
 *
 * @var array
 */
protected $listen = [
    'Laravel\Passport\Events\AccessTokenCreated' => [
        'App\Listeners\RevokeOldTokens',
    ],

    'Laravel\Passport\Events\RefreshTokenCreated' => [
        'App\Listeners\PruneOldTokens',
    ],
];

テストTesting

PassportのactingAsメソッドは、現在認証中のユーザーを指定すると同時にスコープも指定します。actingAsメソッドの最初の引数はユーザーのインスタンスで、第2引数はユーザートークンに許可するスコープ配列を指定します。Passport's actingAs method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the actingAs method is the user instance and the second is an array of scopes that should be granted to the user's token:

use App\Models\User;
use Laravel\Passport\Passport;

public function test_servers_can_be_created()
{
    Passport::actingAs(
        User::factory()->create(),
        ['create-servers']
    );

    $response = $this->post('/api/create-server');

    $response->assertStatus(201);
}

PassportのactingAsClientメソッドは、現在認証中のクライアントを指定すると同時にスコープも指定します。actingAsClientメソッドの最初の引数はクライアントインスタンスで、第2引数はクライアントのトークンへ許可するスコープの配列です。Passport's actingAsClient method may be used to specify the currently authenticated client as well as its scopes. The first argument given to the actingAsClient method is the client instance and the second is an array of scopes that should be granted to the client's token:

use Laravel\Passport\Client;
use Laravel\Passport\Passport;

public function test_orders_can_be_retrieved()
{
    Passport::actingAsClient(
        Client::factory()->create(),
        ['check-status']
    );

    $response = $this->get('/api/orders');

    $response->assertStatus(200);
}

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作