PHP-JWT 无状态登陆
余温
2018年04月10日 15时23分
php
安装
composer require firebase/php-jwt"require": { "firebase/php-jwt": "^5.0" }demo:
<?php include "vendor/autoload.php"; use \Firebase\JWT\JWT; $key = "example_keysajkdhsakhdksjahdsahdsakhsajkdksa"; $token = array( "iss" => "http://example.org", "aud" => "http://example.com", "iat" => 1356999524, "nbf" => 1357000000, "id" => '1321231', ); /** * 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. */ $jwt = JWT::encode($token, $key); $decoded = JWT::decode($jwt, $key, array('HS256')); //print_r($jwt); print_r($decoded); /* NOTE: This will now be an object instead of an associative array. To get an associative array, you will need to cast it as such: */ $decoded_array = (array) $decoded; /** * You can add a leeway to account for when there is a clock skew times between * the signing and verifying servers. It is recommended that this leeway should * not be bigger than a few minutes. * * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef */ JWT::$leeway = 60; // $leeway in seconds $decoded = JWT::decode($jwt, $key, array('HS256')); ?>login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆</title> </head> <body> <form action="login.php" method="post"> <input type="text" name="name" placeholder="账号"><br> <input type="password" name="password"><br> <input type="submit" value="登陆"> </form> </body> </html>login.php
<?php /** * Created by PhpStorm. * User: diwuh * Date: 2018/4/4 * Time: 14:17 */ include "vendor/autoload.php"; use Firebase\JWT\JWT; if ($_SERVER['REQUEST_METHOD']== 'POST'){ $name = $_POST['name']; $password = $_POST['password']; if (md5($password) == md5('123456')){ $key = "example_keysajkdhsakhdksjahdsahdsakhsajkdksa"; $token = array( "iss" => "http://example.org", "aud" => "http://example.com", "iat" => time(), "nbf" => time(), "past_time" => time()+60*60*24*1, "id" => ' ', "name" => $name ); $jwt = JWT::encode($token, $key); setcookie("jwt", $jwt, time()+3600); header('Refresh:1,Url=index.php'); echo '登陆成功';exit(); }else{ header('Refresh:2,Url=login.html'); echo '密码错误';exit(); } }else{ header('Refresh:2,Url=login.html'); echo '请登录';exit(); }index.php
<?php include "vendor/autoload.php"; use \Firebase\JWT\JWT; $key = "example_keysajkdhsakhdksjahdsahdsakhsajkdksa"; $jwt = $_COOKIE['jwt']; $decoded = JWT::decode($jwt, $key,array('HS256')); if ($decoded->past_time < time()){ header('Refresh:2,Url=login.html'); echo '请登陆';exit(); } if ($decoded->name == '余温'){ echo '你好'.$decoded->name; }else{ header('Refresh:2,Url=login.html'); echo '请登陆';exit(); }
//phpURL跳转
header("Location:$urls");exit;
//1秒后跳转
header('Refresh:2,Url=login.html');
下一篇:
jquery 图片上传
请登陆后评论
{{vo.time}} 回复