Readouble

Laravel 9.x Laravel Socialite

イントロダクションIntroduction

Laravelは、一般的なフォームベースの認証に加えて、Laravel Socialite(ソーシャライト:名士)を使用したOAuthプロバイダで認証するためのシンプルで便利な方法も提供します。Socialiteは現在、Facebook、Twitter、LinkedIn、Google、GitHub、GitLab、Bitbucketでの認証をサポートしています。In addition to typical, form based authentication, Laravel also provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite[https://github.com/laravel/socialite]. Socialite currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, and Bitbucket.

lightbulb Note:他のプラットフォームのアダプタは、コミュニティにより管理されているSocialiteプロバイダWebサイトから利用できます。Note
Adapters for other platforms are available via the community driven Socialite Providers[https://socialiteproviders.com/] website.

インストールInstallation

Socialiteを使い始めるには、Composerパッケージマネージャを使用して、プロジェクトの依存関係へパッケージを追加します。To get started with Socialite, use the Composer package manager to add the package to your project's dependencies:

composer require laravel/socialite

SocialiteのアップグレードUpgrading Socialite

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

設定Configuration

Socialiteを使用する前に、アプリケーションが利用するOAuthプロバイダの認証情報を追加する必要があります。通常、これらの認証情報は、認証するサービスのダッシュボード内で「開発者用アプリケーション」を作成することで取得できます。Before using Socialite, you will need to add credentials for the OAuth providers your application utilizes. Typically, these credentials may be retrieved by creating a "developer application" within the dashboard of the service you will be authenticating with.

こうした認証情報は、アプリケーションのconfig/services.php設定ファイルへ記述します。キーはfacebook, twitter(OAuth1.0)、twitter-oauth-2(OAuth 2.0)、linkedingooglegithubgitlabbitbucketで、アプリケーションで必要なプロバイダによります。These credentials should be placed in your application's config/services.php configuration file, and should use the key facebook, twitter (OAuth 1.0), twitter-oauth-2 (OAuth 2.0), linkedin, google, github, gitlab, or bitbucket, depending on the providers your application requires:

'github' => [
    'client_id' => env('GITHUB_CLIENT_ID'),
    'client_secret' => env('GITHUB_CLIENT_SECRET'),
    'redirect' => 'http://example.com/callback-url',
],

lightbulb Note:redirectオプションが相対パスである場合、自動的に完全なURLへ解決されます。Note
If the redirect option contains a relative path, it will automatically be resolved to a fully qualified URL.

認証Authentication

ルートRouting

OAuthプロバイダを使ってユーザーを認証するには、OAuthプロバイダへユーザーをリダイレクトするルートと、認証後にプロバイダからのコールバックを受け取るルートの2つが必要になります。以下のルート例では、両方のルートを実装しています。To authenticate users using an OAuth provider, you will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. The example routes below demonstrate the implementation of both routes:

use Laravel\Socialite\Facades\Socialite;

Route::get('/auth/redirect', function () {
    return Socialite::driver('github')->redirect();
});

Route::get('/auth/callback', function () {
    $user = Socialite::driver('github')->user();

    // $user->token
});

Socialiteファサードが提供するredirectメソッドは、ユーザーをOAuthプロバイダへリダイレクトします。一方、userメソッドは受信リクエストを調べ、そのリクエストの認証を承認した後に、プロバイダからユーザー情報を取得します。The redirect method provided by the Socialite facade takes care of redirecting the user to the OAuth provider, while the user method will examine the incoming request and retrieve the user's information from the provider after they have approved the authentication request.

認証と保存Authentication & Storage

OAuthプロバイダからユーザーを取得したら、そのユーザーがアプリケーションのデータベースに存在するかを判断し、ユーザーを認証します。ユーザーがアプリケーションのデータベースに存在していない場合は通常、そのユーザーを表す新しいレコードをデータベースに作成します。Once the user has been retrieved from the OAuth provider, you may determine if the user exists in your application's database and authenticate the user[/docs/{{version}}/authentication#authenticate-a-user-instance]. If the user does not exist in your application's database, you will typically create a new record in your database to represent the user:

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

Route::get('/auth/callback', function () {
    $githubUser = Socialite::driver('github')->user();

    $user = User::updateOrCreate([
        'github_id' => $githubUser->id,
    ], [
        'name' => $githubUser->name,
        'email' => $githubUser->email,
        'github_token' => $githubUser->token,
        'github_refresh_token' => $githubUser->refreshToken,
    ]);

    Auth::login($user);

    return redirect('/dashboard');
});

lightbulb Note:特定のOAuthプロバイダからどんなユーザー情報が得られるかについては、ユーザー情報の取得ドキュメントを参照してください。Note
For more information regarding what user information is available from specific OAuth providers, please consult the documentation on retrieving user details[#retrieving-user-details].

アクセススコープAccess Scopes

ユーザーをリダイレクトする前に、scopesメソッドを使用し、認証リクエストに含めるべき「スコープ」を指定できます。このメソッドは、以前に指定したすべてのスコープを、指定したスコープとマージします。Before redirecting the user, you may use the scopes method to specify the "scopes" that should be included in the authentication request. This method will merge all previously specified scopes with the scopes that you specify:

use Laravel\Socialite\Facades\Socialite;

return Socialite::driver('github')
    ->scopes(['read:user', 'public_repo'])
    ->redirect();

setScopesメソッドを使用して、認証リクエストの既存のスコープをすべて上書きできます。You can overwrite all existing scopes on the authentication request using the setScopes method:

return Socialite::driver('github')
    ->setScopes(['read:user', 'public_repo'])
    ->redirect();

オプションのパラメータOptional Parameters

多くのOAuthプロバイダがリダイレクトリクエスト中で、その他にもオプションパラメータをサポートしています。リクエストにオプションパラメータを含めるには、withメソッドを呼び出し、連想配列を渡します。A number of OAuth providers support other optional parameters on the redirect request. To include any optional parameters in the request, call the with method with an associative array:

use Laravel\Socialite\Facades\Socialite;

return Socialite::driver('google')
    ->with(['hd' => 'example.com'])
    ->redirect();

warning Warning! withメソッド使用時は、stateresponse_typeなどの予約キーワードを渡さないように注意してください。Warning
When using the with method, be careful not to pass any reserved keywords such as state or response_type.

ユーザー詳細情報の取得Retrieving User Details

ユーザーをアプリケーションの認証コールバックルートへリダイレクトした後、Socialiteのuserメソッドを使用してユーザーの詳細を取得できます。userメソッドが返すユーザーオブジェクトは、ユーザーに関する情報をデータベースへ保存するために使用できる様々なプロパティやメソッドを提供します。After the user is redirected back to your application's authentication callback route, you may retrieve the user's details using Socialite's user method. The user object returned by the user method provides a variety of properties and methods you may use to store information about the user in your own database.

認証につかうOAuthプロバイダが、OAuth1.0とOAuth2.0のどちらをサポートしているかにより、このオブジェクトで利用できるプロパティやメソッドが異なります。Differing properties and methods may be available on this object depending on whether the OAuth provider you are authenticating with supports OAuth 1.0 or OAuth 2.0:

use Laravel\Socialite\Facades\Socialite;

Route::get('/auth/callback', function () {
    $user = Socialite::driver('github')->user();

    // OAuth2.0プロバイダ
    $token = $user->token;
    $refreshToken = $user->refreshToken;
    $expiresIn = $user->expiresIn;

    // OAuth1.0プロバイダ
    $token = $user->token;
    $tokenSecret = $user->tokenSecret;

    // 両プロバイダ
    $user->getId();
    $user->getNickname();
    $user->getName();
    $user->getEmail();
    $user->getAvatar();
});

トークンからのユーザー詳細情報の取得(OAuth2)Retrieving User Details From A Token (OAuth2)

ユーザーの有効なアクセストークンを既に持っている場合は、SocialiteのuserFromTokenメソッドを使用してユーザーの詳細を取得できます。If you already have a valid access token for a user, you can retrieve their user details using Socialite's userFromToken method:

use Laravel\Socialite\Facades\Socialite;

$user = Socialite::driver('github')->userFromToken($token);

トークンとSecretからのユーザー詳細情報の取得(OAuth1)Retrieving User Details From A Token And Secret (OAuth1)

ユーザーの有効なトークンとシークレットが既にある場合は、SocialiteのuserFromTokenAndSecretメソッドを使用してユーザーの詳細を取得できます。If you already have a valid token and secret for a user, you can retrieve their user details using Socialite's userFromTokenAndSecret method:

use Laravel\Socialite\Facades\Socialite;

$user = Socialite::driver('twitter')->userFromTokenAndSecret($token, $secret);

ステートレス認証Stateless Authentication

statelessメソッドを使用すると、セッション状態の確認を無効にできます。これは、クッキーベースのセッションを利用しないステートレスAPIに、ソーシャル認証を追加する場合に有用です。The stateless method may be used to disable session state verification. This is useful when adding social authentication to a stateless API that does not utilize cookie based sessions:

use Laravel\Socialite\Facades\Socialite;

return Socialite::driver('google')->stateless()->user();

warning Warning! Twitter OAuth.0ドライバでは、ステートレス認証は利用できません。Warning
Stateless authentication is not available for the Twitter OAuth 1.0 driver.

章選択

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作