Readouble

Laravel 5.5 API認証(Passport)

イントロダクションIntroduction

Laravelでは古典的なログインフォームによる認証は、簡単に実行できるようになっています。では、APIに関してはどうでしょうか? 通常APIでは、ユーザーの認証にトークンを使用し、リクエスト間のセッション状態は保持されません。Laravelアプリケーションのために、完全なOAuth2サーバの実装を提供するLaravel Passportを使えば、短時間で簡単にAPI認証ができます。Passportは、Alex Bilbieによりメンテナンスされている、League OAuth2サーバ上に構築しています。Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which 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 Alex Bilbie.

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 and features of OAuth2 before continuing.

インストールInstallation

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

composer require laravel/passport=~4.0

Passportサービスプロバイダはフレームワークに対し、自身のマイグレーションディレクトリを登録します。そのためにプロバイダを登録後、データベースのマイグレーションを実行する必要があります。Passportのマイグレーションは、アプリケーションで必要となる、クライアントとアクセストークンを保存しておくテーブルを作成します。The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after registering the provider. The Passport migrations will create the tables your application needs to store clients and access tokens:

php artisan migrate

Note: note Passportのデフォルトマイグレーションを使用しない場合は、AppServiceProviderregisterメソッドの中で、Passport::ignoreMigrationsを呼び出してください。デフォルトのマイグレーションは、php artisan vendor:publish --tag=passport-migrationsを使えばエクスポートできます。{note} If you are not going to use Passport's default migrations, you should call the Passport::ignoreMigrations method in the register method of your AppServiceProvider. You may export the default migrations using php artisan vendor:publish --tag=passport-migrations.

次に、passport:installコマンドを実行します。このコマンドは安全なアクセストークンを生成するのに必要な暗号キーを作成します。さらにアクセストークンを生成するために使用する、「パーソナルアクセス」クライアントと「パスワードグラント」クライアントも作成します。Next, you should run the passport:install 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

このコマンドを実行後、App\UserモデルへLaravel\Passport\HasApiTokensトレイトを追加してください。このトレイトは認証済みユーザーのトークンとスコープを確認するためのヘルパメソッドをモデルに提供します。After running this command, add the Laravel\Passport\HasApiTokens trait to your App\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:

<?php

namespace App;

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

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

次に、AuthServiceProviderbootメソッドから、Passport::routesメソッドを呼び出す必要があります。このメソッドはアクセストークンの発行、アクセストークンの失効、クライアントとパーソナルアクセストークンの管理のルートを登録します。Next, you should call the Passport::routes method within the boot method of your 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 Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

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

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

        Passport::routes();
    }
}

最後に、config/auth.php設定ファイル中で、ガードのapi認証のdriverオプションをpassportへ変更します。これにより、認証のAPIリクエストが送信された時に、パスポートのTokenGuardを使用するように、アプリケーションへ指示します。Finally, in your 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',
    ],
],

フロントエンド・クイックスタートFrontend Quickstart

Note: note パスポートVueコンポーネントを使用するには、Vue JavaScriptフレームワークを使用する必要があります。コンポーネントはBootstrap CSSフレームワークを使用しています。皆さんがこれらのツールを使用しない場合でも、フロントエンド実装の参考として、これらのコンポーネントは役立つでしょう。{note} In order to use the Passport Vue components, you must be using the Vue[https://vuejs.org] JavaScript framework. These components also use the Bootstrap CSS framework. However, even if you are not using these tools, the components serve as a valuable reference for your own frontend implementation.

パスポートは皆さんのユーザーへ、クライアントとパーソナルアクセストークンを作成するために使用するJSON APIを初めから提供しています。しかし、こうしたAPIに関連するフロントエンドをコーディングするには時間を要します。そこで、Passportは実装例、もしくは実装の開始地点として役立ててもらうため、Vueコンポーネントも用意しています。Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens. However, it can be time consuming to code a frontend to interact with these APIs. So, Passport also includes pre-built Vue[https://vuejs.org] components you may use as an example implementation or starting point for your own implementation.

Passport Vueコンポーネントを公開(Laravel用語で開発者が変更可能なリソースを用意すること)するには、vendor:publish Artisanコマンドを使用します。To publish the Passport Vue components, use the vendor:publish Artisan command:

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

公開されたコンポーネントは、resources/assets/js/componentsディレクトリへ設置されます。公開したコンポーネントは、resources/assets/js/app.jsファイルで登録してください。The published components will be placed in your resources/assets/js/components directory. Once the components have been published, you should register them in your resources/assets/js/app.js file:

Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

コンポーネントを登録したら、アセットを再コンパイルするためnpm run devを確実に実行してください。アセットの再コンパイルが済んだら、クライアントとパーソナルアクセストークンを作成し始めるために、アプリケーションのテンプレートへコンポーネントを指定しましょう。After registering the components, make sure to run npm run dev to recompile your assets. Once you have recompiled your assets, you may drop the components into one of your application's templates to get started creating clients and personal access tokens:

<passport-clients></passport-clients>
<passport-authorized-clients></passport-authorized-clients>
<passport-personal-access-tokens></passport-personal-access-tokens>

PassportのデプロイDeploying Passport

Passportを実働サーバへ最初にデプロイするとき、passport:keysコマンドを実行する必要があるでしょう。このコマンドは、Passportがアクセストークンを生成するために必要な、暗号化キーを生成するコマンドです。生成されたキーは、通常ソースコントロールには含めません。When deploying Passport to your production 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 token. The generated keys are not typically kept in source control:

php artisan passport:keys

設定Configuration

トークン持続時間Token Lifetimes

デフォルトでPassportは、再生成する必要のない、長期間持続するアクセストークンを発行します。トークンの持続時間をもっと短くしたい場合は、tokensExpireInrefreshTokensExpireInメソッドを使ってください。これらのメソッドは、AuthServiceProviderbootメソッドから呼び出してください。By default, Passport issues long-lived access tokens that never need to be refreshed. If you would like to configure a shorter token lifetime, you may use the tokensExpireIn and refreshTokensExpireIn methods. These methods should be called from the boot method of your AuthServiceProvider:

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

    Passport::routes();

    Passport::tokensExpireIn(now()->addDays(15));

    Passport::refreshTokensExpireIn(now()->addDays(30));
}

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

OAuth2で認可コードを使いこなせるかは、どの程度開発者がOAuth2に慣れているかによります。認可コードを使用する時、クライアントアプリケーションはそのクライアントに対するアクセストークン発行のリクエストが許可されようと、拒絶されようと、あなたのサーバにそのユーザーをリダイレクトします。Using OAuth2 with 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

JSON APIJSON API

皆さんのアプリのユーザーはclientコマンドを使用できないわけですから、Passportはクライアント作成のJSON APIを提供しています。これにより、クライアントを作成、更新、削除するコントローラをわざわざコードする手間を省略できます。Since your 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/mzabriskie/axios] to demonstrate making HTTP requests to the endpoints.

lightbulb">Tip!! クライアント管理のフロントエンドを自分で実装したくなければ、フロントエンド・クイックスタートを使い、短時間で完全に機能するフロントエンドを用意できます。{tip} If you don't want to implement the entire client management frontend yourself, you can use the frontend quickstart[#frontend-quickstart] to have a fully functional frontend in a matter of minutes.

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:

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

    return redirect('http://your-app.com/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のビューを公開(Laravel用語でリソースを用意すること)する必要があります。公開されたビューは、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 resources/views/vendor/passport:

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

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

ユーザーが許可リクエストを承認したら、API使用側アプリケーションへリダイレクトされます。使用側はあなたのアプリケーションへ、アクセストークンをリクエストするため、POSTリクエストを送信する必要があります。そのリクエストには、ユーザーが許可リクエストを承認した時にあなたのアプリケーションが発行した、許可コードを含める必要があります。この例として、Guzzle HTTPライブラリでPOSTリクエストを作成してみましょう。If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should then 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. In this example, we'll use the Guzzle HTTP library to make the POST request:

Route::get('/callback', function (Request $request) {
    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'redirect_uri' => 'http://example.com/callback',
            'code' => $request->code,
        ],
    ]);

    return json_decode((string) $response->getBody(), true);
});

この/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.

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

アプリケーションが短い有効期限のアクセストークンを発行している場合に、ユーザーはアクセストークンを発行する時に提供しているリフレッシュトークンを使用し、アクセストークンをリフレッシュする必要が起きます。以下はGuzzle HTTPライブラリを使用し、トークンをリフレッシュする例です。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. In this example, we'll use the Guzzle HTTP library to refresh the token:

$http = new GuzzleHttp\Client;

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

return json_decode((string) $response->getBody(), true);

この/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.

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

OAuth2のパスワードグラントはモバイルアプリケーションのような、その他のファーストパーティクライアントへ、メールアドレス/ユーザー名とパスワードを使ったアクセストークンの取得を提供します。これによりOAuth2のAuthozization Codeリダイレクトフローに完全に従うことをユーザーへ要求せずとも、アクセストークンを安全に発行できます。The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an e-mail 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

パスワードグラントによりあなたのアプリケーションがトークンを発行できるようにする前に、パスワードグラントクライアントを作成する必要があります。それには、passport:clientコマンドで--passwordを使用してください。すでに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 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:

$http = new GuzzleHttp\Client;

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

return json_decode((string) $response->getBody(), true);

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を返します。このスコープは「パスワード」グラントを使って発行されたトークのみに割り付けるのが良いでしょう。When using the password 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 grant:

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

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

暗黙のグラントは認可コードのグラントと似ています。違いは認可コードの交換をせずにクライアントへトークンが返されることです。一般的にこのグラントは、JavaScriptやモバイルアプリケーションでクライアントの認証情報を安全に保存できない場合に使用します。このグラントを有効にするには、AuthServiceProviderenableImplicitGrantメソッドを呼び出します。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 your AuthServiceProvider:

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

    Passport::routes();

    Passport::enableImplicitGrant();
}

グラントを有効にしたら、開発者はあなたのアプリケーションからのアクセストークンをリクエストするために、クライアントIDを使うことになるでしょう。使用側アプリケーションは、あなたのアプリケーションの/oauth/authorizeルートへのリダイレクトリクエストを生成する必要があります。例を確認してください。Once a 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:

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

    return redirect('http://your-app.com/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によりメンテナンスタスクを実行する、定期実行ジョブに使用できます。このメソッドを使用するには、最初にapp/Http/Kernel.php$routeMiddlewareを新たに追加する必要があります。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. To use this method you first need to add new middleware to your $routeMiddleware in app/Http/Kernel.php:

use Laravel\Passport\Http\Middleware\CheckClientCredentials;

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

次に、このミドルウェアをルートへ指定します。Then attach this middleware to a route:

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

トークンを取得するには、oauth/tokenエンドポイントへリクエストを作成します。To retrieve a token, make a request to the oauth/token endpoint:

$guzzle = new GuzzleHttp\Client;

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

return json_decode((string) $response->getBody(), true)['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.

Note: note パーソナルアクセストークンは常に長期間有効です。tokensExpireInrefreshTokensExpireInメソッドを使用しても、有効期間を変更できません。{note} Personal access tokens are always long-lived. Their lifetime is not modified when using the tokensExpireIn or refreshTokensExpireIn methods.

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

あなたのアプリケーションでパーソナルアクセストークンを発行できるようにする前に、パーソナルアクセスクライアントを作成する必要があります。--personalオプションを付け、passport:clientコマンドを実行すれば、作成できます。passport:installコマンドを実行済みの場合、このコマンドを実行する必要はありません。Before your application can issue personal access tokens, you will need to create a personal access client. You may do this using the passport:client 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

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

パーソナルアクセスクライアントを作成したら、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 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:

$user = App\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.

lightbulb">Tip!! パーソナルアクセストークンのフロントエンドを自分自身で実装したくない場合は、フロントエンドクイックスタートを使用して、短時間に完全な機能を持つフロントエンドを用意できます。{tip} If you don't want to implement the personal access token frontend yourself, you can use the frontend quickstart[#frontend-quickstart] to have a fully functional frontend in a matter of minutes.

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 delete 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 delete 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 require a valid access token:

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

アクセストークンの受け渡し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:

$response = $client->request('GET', '/api/user', [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer '.$accessToken,
    ],
]);

トークンのスコープToken Scopes

スコープの定義Defining 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.

AuthServiceProviderbootメソッドの中で、Passport::tokensCanメソッドを用い、皆さんのAPIのスコープを定義できます。tokenCanメソッドはスコープ名とスコープの説明の配列を引数に取ります。スコープの説明はお望み通りに記述でき、許可の承認ページでユーザーに表示されます。You may define your API's scopes using the Passport::tokensCan method in the boot method of your AuthServiceProvider. 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:

use Laravel\Passport\Passport;

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

トークンへのスコープ割り付け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://your-app.com/oauth/authorize?'.$query);
});

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

UserモデルのcreateTokenメソッドを使用し、パーソナルアクセストークンを発行する場合、メソッドの第2引数として希望するスコープを配列で渡します。If you are issuing personal access tokens using the 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('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('scope:check-status,place-orders');

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

アクセストークンが確認されたリクエストがアプリケーションにやってきた後でも、認証済みの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 User instance:

use Illuminate\Http\Request;

Route::get('/orders', function (Request $request) {
    if ($request->user()->tokenCan('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にはこれを皆さんに変わって処理するミドルウェアが用意してあります。必要なのは、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:

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

このPassportミドルウェアはlaravel_tokenクッキーを送信するレスポンスへ付加します。このクッキーはPassportが、皆さんのJavaScriptアプリケーションからのAPIリクエストを認可するために使用する、暗号化されたJWTを含んでいます。これで、アクセストークンを明示的に渡さなくても、あなたのアプリケーションのAPIへリクエストを作成できるようになります。This Passport 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. Now, 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);
    });

この認証方法を使用する場合、デフォルトのLaravel JavaScriptスカフォールドはAxiosに対し、常にX-CSRF-TOKENX-Requested-Withヘッダを送るように指示します。しかし、確実にCSRFトークンをHTMLメタタグへ含めてください。When using this method of authentication, the default Laravel JavaScript scaffolding instructs Axios to always send the X-CSRF-TOKEN and X-Requested-With headers. However, you should be sure to include your CSRF token in a HTML meta tag[/docs/{{version}}/csrf#csrf-x-csrf-token]:

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
};

Note: note 他のJavaScriptフレームワークを使用している場合、送信する各リクエストにX-CSRF-TOKENX-Requested-Withヘッダを送るよう、確実に設定してください。{note} If you are using a different JavaScript framework, you should make sure it is configured to send the X-CSRF-TOKEN and X-Requested-With headers with every outgoing request.

イベントEvents

Passportはアクセストークン発酵時とトークンリフレッシュ時にイベントを発行します。これらのイベントをデータベース状の他のアクセストークンを破棄したり、無効にしたりするために使用できます。アプリケーションの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. You may attach listeners to these events in your application's EventServiceProvider:

/**
 * アプリケーションにマップされたイベントリスナ
 *
 * @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:

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

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

    $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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作