PHP-JWTライブラリを用いてAuth0のWEBアプリケーションを作成する


まず、Auth0無料登録を行い、Applicationを作成する(この記事ではhasami.jp.auth0.com)


ログイン(authorization-code-flow)

http://openid-foundation-japan.github.io/openid-connect-core-1_0.ja.html#AuthRequest

AUTHORIZEエンドポイントへGETリクエストすることでログイン画面へ遷移

https://auth0.com/docs/api/authentication#authorization-code-flow

GET "https://hasami.jp.auth0.com/authorize?client_id=DJjstTQAtZsX2mF1WucvC0925YTrNDol&response_type=code&scope=openid+email+profile&redirect_uri=https%3A%2F%2Fmail.hasami.uk%2Fcallback%2F"

(これがログインボタンのリンクになる)

  • response_type = code
  • client_id = DJjstTQAtZsX2mF1WucvC0925YTrNDol(Auth0のApplicationsの設定で取得できます)
  • scope = openid profile email
  • redirect_uri = https://mail.hasami.uk/callback/

https://github.com/fujio-ux/login-auth0-php/blob/master/document-root/index.html

ログイン画面でログイン成功ときに得られるコールバック画面に付与されるGETパラメータ(code)をトークンに変換する

https://auth0.com/docs/api/authentication#authorization-code-flow45

http://openid-foundation-japan.github.io/openid-connect-core-1_0.ja.html#TokenRequest

POST "https://hasami.jp.auth0.com/oauth/token"

  • client_id
  • client_secret
  • grant_type = authorization_code
  • code = コールバックページ(/callback/)のGETパラメータ
  • redirect_uri = authorizeで投げたものと同じものを指定するhttps://mail.hasami.uk/callback/

https://github.com/fujio-ux/login-auth0-php/blob/master/php-include_path/functions.php

PHP-JWTライブラリでAuth0のユニバーサルログイン画面からの戻りで得られるIDトークンを検証(デコード)する

Auth0 が公開しているPHP-SDKはPHP7でないといけない。(https://auth0.com/docs/libraries/auth0-php)

PHP-JWT(firebase)であればPHP5から8まで対応している!

インストールは

composer require firebase/php-jwt

デコードに必要なPEMキー($publicKey)は テナントのURL/pem で手に入れられる(https://hasami.jp.auth0.com/pem)

use Firebase\JWT\JWT;
require_once("vendor/autoload.php");
try{
    $publicKey = file_get_contents("/usr/share/php/rs256.pem");
    #$decoded_ac = JWT::decode($token["access_token"], $publicKey, array('RS256'));
    //Auth0では、AUTHORIZEエンドポイントにaudienceを指定しなかったら(初期状態)JWT形式ではない(opaque)アクセストークンが返ってくるのでデコードしないこと
    //https://auth0.com/docs/tokens/access-tokens#opaque-access-tokens
    //https://auth0.com/docs/tokens/access-tokens#jwt-access-tokens
    $decoded_id = JWT::decode($token["id_token"], $publicKey, array('RS256'));
}catch(Exception $e){
    //検証できなければログイン失敗
}

https://github.com/fujio-ux/login-auth0-php/blob/master/document-root/callback/index.html