0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Day16 — Bearer Token と Cookie 認証を比較し、LaravelでJWT認証を実装する

0
Last updated at Posted at 2025-12-15

はじめに

Day15 では、

✅ JWT の仕組み
✅ なぜ SPA × API で使われるのか

を理解しました。

今日は 「どう実装するか」「どの方式を選ぶべきか」 を整理します。

今日のゴール

・Bearer Token と Cookie 認証の違いを説明できる

・JWT 認証を Laravel に組み込める

・認証付き API を叩ける状態にする

Bearer Token 認証とは?

Bearer Token 認証とは、

「このトークンを持っている人=本人」

というシンプルな考え方です。

Authorization: Bearer xxxxx.yyyyy.zzzzz

Cookie 認証との比較

項目 Bearer Token Cookie
保存場所 localStorage / memory ブラウザCookie
CSRF 不要 対策必須
XSS 弱い 強い
SPA 相性◎ 設定が複雑
API 最適 やや重い

👉 API 専用なら Bearer Token が扱いやすい

今回の方針

Laravel API

JWT(Bearer Token)

SPA から Authorization ヘッダーで送信

Laravel に JWT 認証を導入する

ここでは代表的な
👉 tymon/jwt-auth
を使います。

① パッケージをインストール

composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret

② auth 設定を変更

config/auth.php

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

③ User モデルを対応させる

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

ログイン API を作成する

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (!$token = auth('api')->attempt($credentials)) {
        return response()->json([
            'message' => '認証失敗'
        ], 401);
    }

    return response()->json([
        'access_token' => $token,
        'token_type' => 'Bearer',
        'expires_in' => auth('api')->factory()->getTTL() * 60
    ]);
}

認証が必要な API を作る

① ルートに middleware を設定

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

② 認証付きリクエスト例

GET /api/me
Authorization: Bearer xxx.yyy.zzz

動作確認(Postman)

1.ログイン API でトークン取得

2.Authorization ヘッダーに設定

3./api/me にアクセス

4.ユーザー情報が返れば成功 🎉

よくあるハマりポイント

auth() が null

auth()->user(); // null

👉 auth('api') を使っているか確認

トークン期限切れ

{
  "message": "Token has expired"
}

👉 再ログイン or リフレッシュトークン検討

Bearer Token を安全に使うコツ

・HTTPS 必須

・有効期限は短め

・XSS 対策を徹底

・ログアウト時はフロントで破棄

今日のまとめ

・Bearer Token は API 向き

・Cookie 認証は Web 向き

・JWT は Laravel で簡単に導入可能

・auth:api middleware で保護できる

・SPA × API 認証が完成した 🎉

📅 **次回 Day17

次は セキュリティ編の山場 です。

Day17 — CSRFとは?攻撃の仕組みとLaravelがどう守っているか

「なぜ API では CSRF が不要なのか?」
ここをスッキリさせます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?