Readouble

Laravel 8.x Laravel Sanctum

イントロダクションIntroduction

Laravel Sanctum(サンクタム、聖所)は、SPA(シングルページアプリケーション)、モバイルアプリケーション、およびシンプルなトークンベースのAPIに軽い認証システムを提供します。Sanctumを使用すればアプリケーションの各ユーザーは、自分のアカウントに対して複数のAPIトークンを生成できます。これらのトークンには、そのトークンが実行できるアクションを指定するアビリティ/スコープが付与されることもあります。Laravel Sanctum[https://github.com/laravel/sanctum] provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.

仕組みHow It Works

LaravelSanctumは、2つの別々の問題を解決するために存在します。ライブラリを深く掘り下げる前に、それぞれについて説明しましょう。Laravel Sanctum exists to solve two separate problems. Let's discuss each before digging deeper into the library.

APIトークンAPI Tokens

1つ目にSanctumは、OAuthの複雑さなしに、ユーザーにAPIトークンを発行するために使用できるシンプルなパッケージです。この機能は、「パーソナルアクセストークン」を発行するGitHubやその他のアプリケーションに触発されています。たとえば、アプリケーションの「アカウント設定」に、ユーザーが自分のアカウントのAPIトークンを生成できる画面があるとします。Sanctumを使用して、これらのトークンを生成および管理できます。これらのトークンは通常、非常に長い有効期限(年)がありますが、ユーザーはいつでも手動で取り消すことができます。First, Sanctum is a simple package you may use to issue API tokens to your users without the complication of OAuth. This feature is inspired by GitHub and other applications which issue "personal access tokens". For example, imagine the "account settings" of your application has a screen where a user may generate an API token for their account. You may use Sanctum to generate and manage those tokens. These tokens typically have a very long expiration time (years), but may be manually revoked by the user at anytime.

Laravel Sanctumは、ユーザーAPIトークンを単一のデータベーステーブルに保存し、有効なAPIトークンを含む必要があるAuthorizationヘッダを介して受信HTTPリクエストを認証することでこの機能を提供します。Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming HTTP requests via the Authorization header which should contain a valid API token.

SPA認証SPA Authentication

2つ目にSanctumは、Laravelを利用したAPIと通信する必要があるシングルページアプリケーション(SPA)を認証する簡単な方法を提供するために存在します。これらのSPAは、Laravelアプリケーションと同じリポジトリに存在する場合もあれば、Vue CLIまたはNext.jsアプリケーションを使用して作成されたSPAなど、完全に別個のリポジトリである場合もあります。Second, Sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository, such as a SPA created using Vue CLI or a Next.js application.

この機能のために、Sanctumはいかなる種類のトークンも使用しません。代わりに、SanctumはLaravelの組み込みのクッキーベースのセッション認証サービスを使用します。通常、SanctumはLaravelの「web」認証ガードを利用してこれを実現します。これにより、CSRF保護、セッション認証の利点が提供できるだけでなく、XSSを介した認証資格情報の漏洩を保護します。For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel's web authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.

Sanctumは、受信リクエストが自身のSPAフロントエンドから発信された場合にのみクッキーを使用して認証を試みます。Sanctumが受信HTTPリクエストを調べるとき、最初に認証クッキーをチェックし、存在しない場合は、Sanctumは有効なAPIトークンのAuthorizationヘッダを調べます。Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend. When Sanctum examines an incoming HTTP request, it will first check for an authentication cookie and, if none is present, Sanctum will then examine the Authorization header for a valid API token.

lightbulb">Tip!! SanctumをAPIトークン認証のみ、またはSPA認証のみに使用することはまったく問題ありません。Sanctumを使用しているからといって、Sanctumが提供する両方の機能を使用する必要があるわけではありません。{tip} It is perfectly fine to use Sanctum only for API token authentication or only for SPA authentication. Just because you use Sanctum does not mean you are required to use both features it offers.

インストールInstallation

lightbulb">Tip!! Laravelの最新バージョンは、あらかじめLaravel Sanctumを含んでいます。ただし、アプリケーションのcomposer.jsonファイルがlaravel/sanctumを含んでいない場合は、以下のインストール手順に従ってください。{tip} The most recent versions of Laravel already include Laravel Sanctum. However, if your application's composer.json file does not include laravel/sanctum, you may follow the installation instructions below.

Laravel Sanctumは、Composerパッケージマネージャーを介してインストールできます。You may install Laravel Sanctum via the Composer package manager:

composer require laravel/sanctum

次に、vendor:publish Artisanコマンドを使用してSanctum設定ファイルと移行ファイルをリソース公開する必要があります。sanctum設定ファイルは、アプリケーションのconfigディレクトリに配置されます。Next, you should publish the Sanctum configuration and migration files using the vendor:publish Artisan command. The sanctum configuration file will be placed in your application's config directory:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

最後に、データベースのマイグレーションを実行する必要があります。Sanctumは、APIトークンを格納するための1つのデータベーステーブルを作成します。Finally, you should run your database migrations. Sanctum will create one database table in which to store API tokens:

php artisan migrate

次に、Sanctumを使用してSPAを認証する場合は、Sanctumのミドルウェアをアプリケーションのapp/Http/Kernel.phpファイル内のapiミドルウェアグループに追加する必要があります。Next, if you plan to utilize Sanctum to authenticate an SPA, you should add Sanctum's middleware to your api middleware group within your application's app/Http/Kernel.php file:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

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

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

設定Configuration

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

通常は必須ではありませんが、Sanctumが内部で使用するPersonalAccessTokenモデルを自由に拡張できます。Although not typically required, you are free to extend the PersonalAccessToken model used internally by Sanctum:

use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;

class PersonalAccessToken extends SanctumPersonalAccessToken
{
    // ...
}

次に、Sanctumが提供するusePersonalAccessTokenModelメソッドを使用して、カスタムモデルを使用するようにSanctumに指示します。通常、このメソッドは、アプリケーションのサービスプロバイダの1つのbootメソッドで呼び出す必要があります。Then, you may instruct Sanctum to use your custom model via the usePersonalAccessTokenModel method provided by Sanctum. Typically, you should call this method in the boot method of one of your application's service providers:

use App\Models\Sanctum\PersonalAccessToken;
use Laravel\Sanctum\Sanctum;

/**
 * 全アプリケーションサービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
}

APIトークン認証API Token Authentication

lightbulb">Tip!! 独自のファーストパーティSPAを認証するためにAPIトークンを使用しないでください。代わりに、Sanctumの組み込みのSPA認証機能を使用してください。{tip} You should not use API tokens to authenticate your own first-party SPA. Instead, use Sanctum's built-in SPA authentication features[#spa-authentication].

APIトークンの発行Issuing API Tokens

Sanctumを使用すると、アプリケーションへのAPIリクエストの認証に使用できるAPIトークン/パーソナルアクセストークンを発行できます。APIトークンを使用してリクエストを行う場合、トークンは「Bearer」トークンとして「Authorization」ヘッダに含める必要があります。Sanctum allows you to issue API tokens / personal access tokens that may be used to authenticate API requests to your application. When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.

ユーザーへのトークンの発行を開始するには、ユーザーモデルでLaravel\Sanctum\HasApiTokensトレイトを使用する必要があります。To begin issuing tokens for users, your User model should use the Laravel\Sanctum\HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;

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

トークンを発行するには、createTokenメソッドを使用します。createTokenメソッドはLaravel\Sanctum\NewAccessTokenインスタンスを返します。APIトークンは、データベースに保存する前にSHA-256ハッシュを使用してハッシュしますが、NewAccessTokenインスタンスのplainTextTokenプロパティを使用してトークンのプレーンテキスト値にアクセスできます。トークンが作成された直後に、この値をユーザーに表示する必要があります。To issue a token, you may use the createToken method. The createToken method returns a Laravel\Sanctum\NewAccessToken instance. API tokens are hashed using SHA-256 hashing before being stored in your database, but you may access the plain-text value of the token using the plainTextToken property of the NewAccessToken instance. You should display this value to the user immediately after the token has been created:

use Illuminate\Http\Request;

Route::post('/tokens/create', function (Request $request) {
    $token = $request->user()->createToken($request->token_name);

    return ['token' => $token->plainTextToken];
});

HasApiTokensトレイトが提供するtokens Eloquentリレーションを使用して、ユーザーのすべてのトークンにアクセスできます。You may access all of the user's tokens using the tokens Eloquent relationship provided by the HasApiTokens trait:

foreach ($user->tokens as $token) {
    //
}

トークンのアビリティToken Abilities

Sanctumでは、トークンに「アビリティ」を割り当てることができます。アビリティはOAuthの「スコープ」と同様の目的を果たします。能力の文字列配列をcreateTokenメソッドの2番目の引数として渡すことができます。Sanctum allows you to assign "abilities" to tokens. Abilities serve a similar purpose as OAuth's "scopes". You may pass an array of string abilities as the second argument to the createToken method:

return $user->createToken('token-name', ['server:update'])->plainTextToken;

Sanctumが認証した受信リクエストを処理する場合、tokenCanメソッドを使用して、トークンに特定の機能があるかを判定できます。When handling an incoming request authenticated by Sanctum, you may determine if the token has a given ability using the tokenCan method:

if ($user->tokenCan('server:update')) {
    //
}

トークンアビリティミドルウェアToken Ability Middleware

また、Sanctumには2つのミドルウェアが含まれており、受信リクエストが指定するアビリティが付与されたトークンで認証されているかどうかを確認するために使用できます。まずは、アプリケーションの app/Http/Kernel.php ファイルの $routeMiddleware プロパティに以下のミドルウェアを追加します。Sanctum also includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given ability. To get started, add the following middleware to the $routeMiddleware property of your application's app/Http/Kernel.php file:

'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,

受信リクエストのトークンがリストしたすべてのアビリティを持っていることを確認するには、abilitiesミドルウェアをルートへ割り付けます。The abilities middleware may be assigned to a route to verify that the incoming request's token has all of the listed abilities:

Route::get('/orders', function () {
    // トークンは"check-status"と"place-orders"アビリティの両方を持っている
})->middleware(['auth:sanctum', 'abilities:check-status,place-orders']);

abilityミドルウェアは、受信リクエストのトークンに、リストしたアビリティのうち少なくとも1つを持っていることを確認するため、ルートへ割り付けます。The ability middleware may be assigned to a route to verify that the incoming request's token has at least one of the listed abilities:

Route::get('/orders', function () {
    // Token has the "check-status" or "place-orders" ability...
})->middleware(['auth:sanctum', 'ability:check-status,place-orders']);

ファーストパーティのUIが開始したリクエストFirst-Party UI Initiated Requests

利便性のため、受信認証リクエストがファーストパーティSPAからのものであり、Sanctumの組み込みSPA認証を使用している場合、tokenCanメソッドは常にtrueを返します。For convenience, the tokenCan method will always return true if the incoming authenticated request was from your first-party SPA and you are using Sanctum's built-in SPA authentication[#spa-authentication].

しかし、これは必ずしもアプリケーションがユーザーにアクションの実行を許可する必要があるわけではありません。通常、アプリケーションの 認可ポリシー は、トークンがアビリティの実行を許可されているかどうかを判断し、ユーザーインスタンス自身がアクションの実行を許可すべきかどうかをチェックします。However, this does not necessarily mean that your application has to allow the user to perform the action. Typically, your application's authorization policies[/docs/{{version}}/authorization#creating-policies] will determine if the token has been granted the permission to perform the abilities as well as check that the user instance itself should be allowed to perform the action.

たとえば、サーバを管理するアプリケーションを想像してみると、これはトークンがサーバの更新を許可されていること、およびサーバがユーザーに属していることを確認する必要があることを意味します。For example, if we imagine an application that manages servers, this might mean checking that token is authorized to update servers and that the server belongs to the user:

return $request->user()->id === $server->user_id &&
       $request->user()->tokenCan('server:update')

最初は、tokenCanメソッドを呼び出して、ファーストパーティのUIが開始したリクエストに対して常にtrueを返すことは、奇妙に思えるかもしれません。ただ、APIトークンが利用可能であり、tokenCanメソッドにより検査できると常に想定できるため便利です。このアプローチを採用することで、リクエストがアプリケーションのUIからトリガーされたのか、APIのサードパーティコンシューマーの1つによって開始されたのかを気にすることなく、アプリケーションの認可ポリシー内で常にtokenCanメソッドを呼び出すことができます。At first, allowing the tokenCan method to be called and always return true for first-party UI initiated requests may seem strange; however, it is convenient to be able to always assume an API token is available and can be inspected via the tokenCan method. By taking this approach, you may always call the tokenCan method within your application's authorizations policies without worrying about whether the request was triggered from your application's UI or was initiated by one of your API's third-party consumers.

ルートの保護Protecting Routes

すべての受信リクエストを認証する必要があるようにルートを保護するには、routes/web.phpおよびroutes/api.phpルートファイル内の保護されたルートにsanctum認証ガードをアタッチする必要があります。このガードは、受信リクエストがステートフルなクッキー認証済みリクエストとして認証されるか、リクエストがサードパーティからのものである場合は有効なAPIトークンヘッダを含むことを保証します。To protect routes so that all incoming requests must be authenticated, you should attach the sanctum authentication guard to your protected routes within your routes/web.php and routes/api.php route files. This guard will ensure that incoming requests are authenticated as either stateful, cookie authenticated requests or contain a valid API token header if the request is from a third party.

アプリケーションのroutes/web.phpファイル内のルートをsanctumガードを使用して認証することを推奨する理由を疑問に思われるかもしれません。Sanctumは、最初にLaravelの一般的なセッション認証クッキーを使用して受信リクエストの認証を試みます。そのクッキーが存在しない場合、SanctumはリクエストのAuthorizationヘッダのトークンを使用してリクエストの認証を試みます。さらに、Sanctumを使用してすべてのリクエストを認証すると、現在認証されているユーザーインスタンスで常にtokenCanメソッドを呼び出すことができます。You may be wondering why we suggest that you authenticate the routes within your application's routes/web.php file using the sanctum guard. Remember, Sanctum will first attempt to authenticate incoming requests using Laravel's typical session authentication cookie. If that cookie is not present then Sanctum will attempt to authenticate the request using a token in the request's Authorization header. In addition, authenticating all requests using Sanctum ensures that we may always call the tokenCan method on the currently authenticated user instance:

use Illuminate\Http\Request;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

トークンの削除Revoking Tokens

Laravel\Sanctum\HasApiTokensトレイトが提供するtokensリレーションを使用してデータベースからトークンを削除することにより、トークンを「取り消す」ことができます。You may "revoke" tokens by deleting them from your database using the tokens relationship that is provided by the Laravel\Sanctum\HasApiTokens trait:

// 全トークンの削除
$user->tokens()->delete();

// 現在のリクエストの認証に使用されたトークンを取り消す
$request->user()->currentAccessToken()->delete();

// 特定のトークンを取り消す
$user->tokens()->where('id', $tokenId)->delete();

SPA認証SPA Authentication

Sanctumは、Laravelを利用したAPIと通信する必要があるシングルページアプリケーション(SPA)を認証する簡単な手段を提供するためにも存在しています。これらのSPAは、Laravelアプリケーションと同じリポジトリに存在する場合もあれば、完全に別個のリポジトリである場合もあります。Sanctum also exists to provide a simple method of authenticating single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository.

この機能のために、Sanctumはいかなる種類のトークンも使用しません。代わりに、SanctumはLaravelの組み込みクッキーベースのセッション認証サービスを使用します。この認証へのアプローチは、CSRF保護、セッション認証の利点を提供するだけでなく、XSSを介した認証資格情報の漏洩から保護します。For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. This approach to authentication provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.

Note: note 認証を行うには、SPAとAPIが同じトップレベルドメインを共有している必要があります。ただし、異なるサブドメインに配置しても構いません。さらに、必ずリクエストへAccept: application/jsonヘッダを付け、送信してください。{note} In order to authenticate, your SPA and API must share the same top-level domain. However, they may be placed on different subdomains. Additionally, you should ensure that you send the Accept: application/json header with your request.

設定Configuration

ファーストパーティドメインの設定Configuring Your First-Party Domains

まず、SPAがリクエストを行うドメインを設定する必要があります。これらのドメインは、sanctum設定ファイルのstateful設定オプションを使用して構成します。この設定は、APIにリクエストを行うときにLaravelセッションクッキーを使用して「ステートフル」な認証を維持するドメインを決定します。First, you should configure which domains your SPA will be making requests from. You may configure these domains using the stateful configuration option in your sanctum configuration file. This configuration setting determines which domains will maintain "stateful" authentication using Laravel session cookies when making requests to your API.

Note: note ポートを含むURL(例:127.0.0.1:8000)を介してアプリケーションにアクセスしている場合は、ドメインにポート番号を含める必要があります。{note} If you are accessing your application via a URL that includes a port (127.0.0.1:8000), you should ensure that you include the port number with the domain.

SanctumミドルウェアSanctum Middleware

次に、Sanctumのミドルウェアをapp/Http/Kernel.phpファイル内のapiミドルウェアグループに追加する必要があります。このミドルウェアは、SPAからの受信リクエストがLaravelのセッションクッキーを使用して認証できるようにすると同時に、サードパーティまたはモバイルアプリケーションからのリクエストがAPIトークンを使用して認証できるようにする役割を果たします。Next, you should add Sanctum's middleware to your api middleware group within your app/Http/Kernel.php file. This middleware is responsible for ensuring that incoming requests from your SPA can authenticate using Laravel's session cookies, while still allowing requests from third parties or mobile applications to authenticate using API tokens:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

CORSとクッキーCORS & Cookies

別のサブドメインで実行されるSPAからのアプリケーションでの認証に問題がある場合は、CORS(クロスオリジンリソースシェアリング)またはセッションクッキー設定を誤って設定している可能性があります。If you are having trouble authenticating with your application from a SPA that executes on a separate subdomain, you have likely misconfigured your CORS (Cross-Origin Resource Sharing) or session cookie settings.

アプリケーションのCORS設定が、値がTrueAccess-Control-Allow-Credentialsヘッダを返しているか確認する必要があります。これは、アプリケーションのconfig/cors.php設定ファイル内のsupports_credentialsオプションをtrueに設定することで実現できます。You should ensure that your application's CORS configuration is returning the Access-Control-Allow-Credentials header with a value of True. This may be accomplished by setting the supports_credentials option within your application's config/cors.php configuration file to true.

さらに、アプリケーションのグローバルなaxiosインスタンスでwithCredentialsオプションを有効にする必要があります。通常、これはresources/js/bootstrap.jsファイルで実行する必要があります。フロントエンドからHTTPリクエストを行うためにAxiosを使用していない場合は、独自のHTTPクライアントで同等の構成を実行する必要があります。In addition, you should enable the withCredentials option on your application's global axios instance. Typically, this should be performed in your resources/js/bootstrap.js file. If you are not using Axios to make HTTP requests from your frontend, you should perform the equivalent configuration on your own HTTP client:

axios.defaults.withCredentials = true;

最後に、アプリケーションのセッションクッキードメイン設定で、ルートドメインのサブドメインを確実にサポートしてください。これを実現するには、アプリケーションのconfig/session.php設定ファイル内でドメインの先頭に.を付けます。Finally, you should ensure your application's session cookie domain configuration supports any subdomain of your root domain. You may accomplish this by prefixing the domain with a leading . within your application's config/session.php configuration file:

'domain' => '.domain.com',

認証Authenticating

CSRF保護CSRF Protection

SPAを認証するには、SPAの「ログイン」ページで最初に/sanctum/csrf-cookieエンドポイントにリクエストを送信して、アプリケーションのCSRF保護を初期化する必要があります。To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application:

axios.get('/sanctum/csrf-cookie').then(response => {
    // ログイン…
});

このリクエスト中に、Laravelは現在のCSRFトークンを含むXSRF-TOKENクッキーをセットします。このトークンは、後続のリクエストへX-XSRF-TOKENヘッダで渡す必要があります。これは、AxiosやAngular HttpClientなどの一部のHTTPクライアントライブラリでは自動的に行います。JavaScript HTTPライブラリで値が設定されていない場合は、このルートで設定されたXSRF-TOKENクッキーの値と一致するようにX-XSRF-TOKENヘッダを手動で設定する必要があります。During this request, Laravel will set an XSRF-TOKEN cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN header on subsequent requests, which some HTTP client libraries like Axios and the Angular HttpClient will do automatically for you. If your JavaScript HTTP library does not set the value for you, you will need to manually set the X-XSRF-TOKEN header to match the value of the XSRF-TOKEN cookie that is set by this route.

ログインLogging In

CSRF保護を初期化したら、Laravelアプリケーションの/loginルートにPOSTリクエストを行う必要があります。この/loginルートは手動で実装するか、またはLaravel Fortifyのようなヘッドレス認証パッケージを使用します。Once CSRF protection has been initialized, you should make a POST request to your Laravel application's /login route. This /login route may be implemented manually[/docs/{{version}}/authentication#authenticating-users] or using a headless authentication package like Laravel Fortify[/docs/{{version}}/fortify].

ログインリクエストが成功すると、認証され、アプリケーションのルートへの後続リクエストは、Laravelアプリケーションがクライアントに発行したセッションクッキーを介して自動的に認証されます。さらに、アプリケーションはすでに/sanctum/csrf-cookieルートにリクエストを送信しているため、JavaScript HTTPクライアントがXSRF-TOKENクッキーの値をX-XSRF-TOKENヘッダで送信する限り、後続のリクエストは自動的にCSRF保護を受けます。If the login request is successful, you will be authenticated and subsequent requests to your application's routes will automatically be authenticated via the session cookie that the Laravel application issued to your client. In addition, since your application already made a request to the /sanctum/csrf-cookie route, subsequent requests should automatically receive CSRF protection as long as your JavaScript HTTP client sends the value of the XSRF-TOKEN cookie in the X-XSRF-TOKEN header.

もちろん、アクティビティがないためにユーザーのセッションが期限切れになった場合、Laravelアプリケーションへの後続のリクエストは401か419HTTPエラー応答を受け取る可能性があります。この場合、ユーザーをSPAのログインページにリダイレクトする必要があります。Of course, if your user's session expires due to lack of activity, subsequent requests to the Laravel application may receive 401 or 419 HTTP error response. In this case, you should redirect the user to your SPA's login page.

Note: note 独自の/loginエンドポイントを自由に作成できます。ただし、標準のLaravelが提供するセッションベースの認証サービスを使用してユーザーを認証していることを確認する必要があります。通常、これはweb認証ガードを使用することを意味します。{note} You are free to write your own /login endpoint; however, you should ensure that it authenticates the user using the standard, session based authentication services that Laravel provides[/docs/{{version}}/authentication#authenticating-users]. Typically, this means using the web authentication guard.

ルートの保護Protecting Routes

すべての受信リクエストを認証する必要があるようにルートを保護するには、routes/api.phpファイル内のAPIルートにsanctum認証ガードを指定する必要があります。このガードは、受信リクエストがSPAからのステートフル認証済みリクエストとして認証されるか、リクエストがサードパーティからのものである場合は有効なAPIトークンヘッダを含むことを保証します。To protect routes so that all incoming requests must be authenticated, you should attach the sanctum authentication guard to your API routes within your routes/api.php file. This guard will ensure that incoming requests are authenticated as either a stateful authenticated requests from your SPA or contain a valid API token header if the request is from a third party:

use Illuminate\Http\Request;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

プライベートブロードキャストチャンネルの認可Authorizing Private Broadcast Channels

SPAがプライベート/プレゼンスブロードキャストチャネルによる認証の必要がある場合は、routes/api.phpファイル内でBroadcast::routesメソッドを呼び出しす必要があります。If your SPA needs to authenticate with private / presence broadcast channels[/docs/{{version}}/broadcasting#authorizing-channels], you should place the Broadcast::routes method call within your routes/api.php file:

Broadcast::routes(['middleware' => ['auth:sanctum']]);

次に、Pusherの許可リクエストを成功させるために、Laravel Echoを初期化するときにカスタムPusher authorizerを提供する必要があります。これにより、アプリケーションは、クロスドメインリクエスト用に適切に設定したaxiosインスタンスを使用するようにPusherを構成できます。Next, in order for Pusher's authorization requests to succeed, you will need to provide a custom Pusher authorizer when initializing Laravel Echo[/docs/{{version}}/broadcasting#client-side-installation]. This allows your application to configure Pusher to use the axios instance that is properly configured for cross-domain requests[#cors-and-cookies]:

window.Echo = new Echo({
    broadcaster: "pusher",
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true,
    key: process.env.MIX_PUSHER_APP_KEY,
    authorizer: (channel, options) => {
        return {
            authorize: (socketId, callback) => {
                axios.post('/api/broadcasting/auth', {
                    socket_id: socketId,
                    channel_name: channel.name
                })
                .then(response => {
                    callback(false, response.data);
                })
                .catch(error => {
                    callback(true, error);
                });
            }
        };
    },
})

モバイルアプリケーション認証Mobile Application Authentication

Sanctumトークンを使用して、APIに対するモバイルアプリケーションのリクエストを認証することもできます。モバイルアプリケーションリクエストを認証するプロセスは、サードパーティのAPIリクエストを認証するプロセスと似ています。ただし、APIトークンの発行方法にはわずかな違いがあります。You may also use Sanctum tokens to authenticate your mobile application's requests to your API. The process for authenticating mobile application requests is similar to authenticating third-party API requests; however, there are small differences in how you will issue the API tokens.

APIトークンの発行Issuing API Tokens

利用開始するには、ユーザーの電子メール/ユーザー名、パスワード、およびデバイス名を受け入れるルートを作成し、それらの資格情報を新しいSanctumトークンと交換します。このエンドポイントに付けられた「デバイス名」は情報提供を目的としたものであり、任意の値にすることができます。一般に、デバイス名の値は、「Nuno'siPhone12」などのユーザーが認識できる名前である必要があります。To get started, create a route that accepts the user's email / username, password, and device name, then exchanges those credentials for a new Sanctum token. The "device name" given to this endpoint is for informational purposes and may be any value you wish. In general, the device name value should be a name the user would recognize, such as "Nuno's iPhone 12".

通常、モバイルアプリケーションの「ログイン」画面からトークンエンドポイントにリクエストを送信します。エンドポイントはプレーンテキストのAPIトークンを返します。このトークンは、モバイルデバイスに保存され、追加のAPIリクエストを行うために使用されます。Typically, you will make a request to the token endpoint from your mobile application's "login" screen. The endpoint will return the plain-text API token which may then be stored on the mobile device and used to make additional API requests:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

Route::post('/sanctum/token', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required',
    ]);

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

    return $user->createToken($request->device_name)->plainTextToken;
});

モバイルアプリケーションがトークンを使用してアプリケーションにAPIリクエストを行う場合、AuthorizationヘッダのトークンをBearerトークンとして渡す必要があります。When the mobile application uses the token to make an API request to your application, it should pass the token in the Authorization header as a Bearer token.

lightbulb">Tip!! モバイルアプリケーションのトークンを発行するときに、トークンのアビリティを自由に指定することもできます。{tip} When issuing tokens for a mobile application, you are also free to specify token abilities[#token-abilities].

ルートの保護Protecting Routes

前述の通り、ルートにsanctum認証ガードを指定することにより、すべての受信リクエストが認証済みであるようにルートを保護できます。As previously documented, you may protect routes so that all incoming requests must be authenticated by attaching the sanctum authentication guard to the routes:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

トークンの削除Revoking Tokens

ユーザーがモバイルデバイスに発行したAPIトークンを取り消すことができるようにするには、WebアプリケーションのUIで「アカウント設定」部分で「取り消す」ボタンと一緒に名前をリストしてください。ユーザーが「取り消す」ボタンをクリックしたら、データベースからトークンを削除できます。Laravel\Sanctum\HasApiTokensトレイトによって提供されるtokensリレーションを介して、ユーザーのAPIトークンにアクセスできることを忘れないでください。To allow users to revoke API tokens issued to mobile devices, you may list them by name, along with a "Revoke" button, within an "account settings" portion of your web application's UI. When the user clicks the "Revoke" button, you can delete the token from the database. Remember, you can access a user's API tokens via the tokens relationship provided by the Laravel\Sanctum\HasApiTokens trait:

// すべてのトークンを取り消す
$user->tokens()->delete();

// 特定のトークンを取り消す
$user->tokens()->where('id', $tokenId)->delete();

テストTesting

テスト中に、Sanctum::actingAsメソッドを使用して、ユーザーを認証し、トークンに付与するアビリティを指定できます。While testing, the Sanctum::actingAs method may be used to authenticate a user and specify which abilities should be granted to their token:

use App\Models\User;
use Laravel\Sanctum\Sanctum;

public function test_task_list_can_be_retrieved()
{
    Sanctum::actingAs(
        User::factory()->create(),
        ['view-tasks']
    );

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

    $response->assertOk();
}

トークンにすべてのアビリティを付与したい場合は、actingAsメソッドへ指定するアビリティリストに*を含める必要があります。If you would like to grant all abilities to the token, you should include * in the ability list provided to the actingAs method:

Sanctum::actingAs(
    User::factory()->create(),
    ['*']
);

章選択

設定

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

ヘッダー項目移動

キーボード操作