LoginSignup
13
10

More than 1 year has passed since last update.

php-jwtを使って認証付きAPIの実装方法

Last updated at Posted at 2021-06-08

php-jwtを使って認証付きAPIの実装方法

概要

ホストAからホストBへの通信で勝手アクセスを防ぐため
アクセスキーを持つプログラムだけが実行できるようにする。

php-jwt導入

php-jwtをcomposerを使いダウンロード

$ composer require firebase/php-jwt

firebase/php-jwt

サンプルコード

サンプルは最近案件で使っているのでCodeigniterベース🙇‍♂️

JWT_Test.php

JWT::encodeでAPP_SECRET_KEYを使いエンコードを行う
JWT::decodeでAPP_SECRET_KEYを使いデコードを行う

use Firebase\JWT\JWT;

const APP_SECRET_KEY = "xxxxxxxxxx";

class JWT_Test
{
    /**
     * APP_SECRET_KEYを使い暗号化を行う
     */
    function encode()
    {
        $payload = array(
            "iss" => "xxx",
            "aud" => "xxx/xxx",
            "iat" => time(),
            "exp" => time() + 3600
        );

        $jwt = JWT::encode($payload, APP_SECRET_KEY);

        return $jwt;
    }

    /**
     * APP_SECRET_KEYを使い復号化を行う
     */
    function decode($jwt)
    {
        $decoded = JWT::decode($jwt, APP_SECRET_KEY, ['HS256']);

        return $decoded;
    }
}

Welcome.php

Guzzleを使いAPIリクエストを行うSSL認証のサイトにアクセスする場合、
'verify' => FCPATH.'cacert.pem' が必要、cacert.pemは以下
Authorizationヘッダーにエンコードしたtokenを付けてアクセス
リクエスト先はAuthorizationヘッダーを取得デコード可能な場合のみ処理を継続
curl - Extract CA Certs from Mozilla

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('JWT_Test');
    }

    /**
     * 本体側 Guzzleを使いヘッダーにトークン付きリクエストを行う
     */
    public function jwt_request()
    {
        $token = $this->JWT_Test->encode();
        $client = new GuzzleHttp\Client([
            'base_uri' => 'https://xxx.xxx.xxx/',
            'verify' => FCPATH.'cacert.pem'
        ]);
        $headers = [
            'Authorization' => $token,
            'Accept' => 'application/json',
        ];

        $response = $client->request('GET', '/sample-acc/welcome/jwt_request_decode', [
            'headers' => $headers
        ]);

        var_dump($response->getBody()->getContents());
    }

    /**
     * レスポンス側 ヘッダーのトークンが復号化可能な場合に処理を継続
     */
    public function jwt_request_decode()
    {
        $headers = apache_request_headers();
        $token = $headers['Authorization'];

        try {
            $result = $this->JWT_Test->decode($token);
            echo json_encode($result);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}

いいね!と思ったら LGTM お願いします :clap::clap::clap:

【PR】週末ハッカソンというイベントやってます! → https://weekend-hackathon.toyscreation.jp/about/

13
10
1

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
10