LoginSignup
13
5

More than 1 year has passed since last update.

Laravel SPA認証 Socialite googleログイン

Last updated at Posted at 2023-01-27

googleログインのSPA認証をしていきます。
GCPプロジェクト作成に関しては省略しています。

①socialite インストール

composer require laravel/socialite 

②クライアントIDとクライアントシークレットを.env作成

.env
GOOGLE_CLIENT_ID=//クライアントID
GOOGLE_CLIENT_SECRET=//クライアントシークレット

③.envをconfig呼び出しにする。ここでredirectURL(google認証画面表示)を指定。

config/services.php
'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('APP_URL') . 'login/google/callback',
    ],

④api/googleを叩いた時に、Googleアカウントの認証ページへユーザーをリダイレクト

リダイレクトのURLを取得しJSONで返します。

route/api.php
Route::get('google', ApiAuthRedirectToGoogleAction::class);
app/Responses/Api/ApiAuthRedirectToGoogleActionResponse.php
    public function response()
    {
        $redirectUrl = Socialite::driver('google')->redirect()->getTargetUrl();

        return response()->json([
            'redirect_url' => $redirectUrl,
        ]);
    }

⑤リダイレクトURLを取得し、URLを叩く

Laravel_URLには、Larave側のURLを入れて下さい

const moveToGoogleOAuth = () => {
  axios
    .get(`${import.meta.env.Laravel_URL}/google`)
    .then((response) => {
      window.location.href = response.data.redirect_url;
    });
};

⑥ フロント側でredirect_urlと同じコンポーネント作成

{
  path: "/login/google/callback",
  name: "RedirectAuthGoogle",
  component: RedirectAuthGoogle,
},

⑦ tokenを受け取って Laravel側にpost

authorization code と state を埋め込んだ状態で Client に渡します。

onMounted(() => {
  axios.get(`${import.meta.env.VITE_SANCTUM_URL}`).then(() => {
    axios
      .post(
        `${import.meta.env.VITE_API_URL}/login/google/callback`,
        {
          code,
          state,
        }
      )
      .then((res) => {
        if (res.data.status_code === "404") {
          router.push("/login");
        } else {
          const token = res.data.access_token;
          localStorage.setItem("auth", token);
          router.push("/home");
        }
      });
  });
});

⑧ google User取得

ここに指定するrouteは、confingで定義したroute

routes/api.php
Route::post('login/google/callback', ApiAuthGoogleCallbackAction::class);

googleユーザー取得

 Socialite::driver('google_2')->stateless()->user();

tokenの検証は、socialiteが内部的にやっています。
↓userメソッド
https://github.com/laravel/socialite/blob/5.x/src/Two/AbstractProvider.php
getUserByTokenでよしなにやってます

13
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
5