LoginSignup
18
18

More than 5 years have passed since last update.

JWT(Json Web Token) をPHPで生成する

Last updated at Posted at 2016-04-19

tl;dr

jwt.png

JWTをPHPで生成してみた。
環境はdockerで作って、そこでお試しして、トークン作成。

環境

Dockerfile作成

FROM php:7.0.5-apache
COPY src/ /var/www/html/

RUN apt-get update && apt-get install -y vim git curl

RUN curl -sS https://getcomposer.org/installer | php

RUN mv composer.phar /usr/local/bin/composer

RUN composer require lcobucci/jwt

EXPOSE 80

コンテナ作成


docker build -t composer-php .
docker run -d --name my-test composer-php

-composer.json

{
 "require": {
 "lcobucci/jwt": "^3.1"
 }
}

コンテナの中身

/var/www/html/src
composer.json
token.php
vendor
 autoload.php
 composer
 lcobucci

トークンを作成するライブラリ(token.php)

lcobucci/jwtを使いました。
https://github.com/lcobucci/jwt

JWTのサイトで全てチェックOKだったので。

php.png

名前空間を利用するために、autoload.phpをrequireしています。


<?php
require_once('vendor/autoload.php');

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;


$signer = new Sha256();

$token = (new Builder())->setIssuer('http://example.com') // Configures the issuer (iss claim)
                        ->setAudience('http://example.org') // Configures the audience (aud claim)
                        ->setId('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
                        ->setIssuedAt(time()) // Configures the time that the token was issue (iat claim)
                        ->setNotBefore(time() + 60) // Configures the time that the token can be used (nbf claim)
                        ->setExpiration(time() + 3600) // Configures the expiration time of the token (exp claim)
                        ->set('uid', 1) // Configures a new claim, called "uid"
                        ->sign($signer, 'testing') // creates a signature using "testing" as key
                        ->getToken(); // Retrieves the generated token


$token->getHeaders(); // Retrieves the token headers
$token->getClaims(); // Retrieves the token claims

echo $token->getHeader('jti'); // will print "4f1g23a12aa"
echo "\r\n";
echo $token->getClaim('iss'); // will print "http://example.com"
echo "\r\n";
echo $token->getClaim('uid'); // will print "1"
echo "\r\n";
echo $token; // The string representation of the object is a JWT string (pretty easy, right?)
echo "\r\n";

php ./token.php

トークンが標準出力に出ました。

トークンの生成については、暗号化のパターンを含め、いくつかあるので仕様に合わせて選択する。
https://github.com/lcobucci/jwt

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