1. 程式人生 > 其它 >jwt 的下載無需複製部落格和部落格園

jwt 的下載無需複製部落格和部落格園

1:瀏覽器輸入jwt 官網

官方地址

https://jwt.io/introduction

2:複製composer 命令

 composer require firebase/php-jwt

3:檔案下載目錄

(1)laravel 下載的檔案位置

(2):tp檔案位置

4:檔案新建一個service 目錄,新建一個TokenService,進行建立方法名稱

<?php


namespace App\service;



class TokenService
{

    /**
     *
     * 建立token
     */
    public
function createToken(){ } /** * * 驗證token */ public function checkToken(){ } }

5:參看MD README.md 進行復制 修改為以下的程式碼,建立token的加入使用者id的形參。

<?php


namespace App\service;

// 第一步引入token
use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class TokenService
{

    /**
     *
     * 建立token
     
*/

public function createToken($userId){ $key = "example_key"; $payload = array( "iss" => "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000, "user_id"=>$userId );
/** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ $token = JWT::encode($payload, $key, 'HS256'); // $decoded = JWT::decode($jwt, new Key($key, 'HS256')); return $token; } /** * * 驗證token */ public function checkToken($token){ $key = "example_key"; $payload = array( "iss" => "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000 ); /** * IMPORTANT: * You must specify supported algorithms for your application. See * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40 * for a list of spec-compliant algorithms. */ // $token = JWT::encode($payload, $key, 'HS256'); $decoded = JWT::decode($token, new Key($key, 'HS256')); return $decoded; } }

6:控制器 根據使用者id進行呼叫即可