1
1

More than 1 year has passed since last update.

【PHP】Laravelの`bearerToken()`メソッドを使ってリクエストヘッダーのBearerトークンを取得

Posted at

概要

LaravelでAPIを開発するときなど、認証時にリクエストヘッダーのトークンを使うことがあると思います。【Laravel8.x】リクエストヘッダーの値を取得する。の記事にある通り、requestからヘッダー値を取得する方法でも全然良いと思うのですが、LaravelではbearerToken()というメソッドが用意されていたので紹介します。

bearerToken()メソッドについて

How to get Bearer token from a request in Laravelのstackoverflowの記事に使い方など書かれています。基本的にはrequestのオブジェクトにメソッドが用意されているので、$token = $request->bearerToken();のような形で取得できます。

実装サンプル

おそらくリクエストヘッダーのトークンを確認するのは、Middlewareで実装するケースが多いと思うので、Middlewareでの実装サンプルを紹介します。

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

use App\Services\UserAccount\UserAccountService;

class AuthenticateToken
{
    // token複合化用のサービスの定義(実装は記載割愛)
    private $userAccountService;
    public function __construct(
        UserAccountService $userAccountService,
    ) {
        $this->userAccountService = $userAccountService;
    }

    public function handle(Request $request, Closure $next)
    {
        // Bearerトークンを取得
        $authToken = $request->bearerToken();

        if (isset($authToken)) {
            // authTokenを複合化&userのidを取得(実装は記載割愛)
            $id = $this->userAccountService->decodeUserIdToken($authToken);
            // Controllerに渡すリクエストにマージ
            $request->merge(['userAccountId' => $id]);
            return $next($request);
        }
        // トークン内容が取得できなかったらエラーを返す
        return response()->json(
            [
                'message' =>  'Can not authorize token'
            ],
            Response::HTTP_UNAUTHORIZED
        );
    }
}
1
1
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
1
1