php-jwt认证
composer require firebase/php-jwt
后端我们使用了一个专门的JWT库:php-jwt
使用composer安装php-jwt,接收到登录用户名和密码后,PHP验证用户名和密码是否正确(实际开发中应该结合数据库,从数据库里拿用户名和密码比对,本实例为了演示只做简单验证),如果用户名和密码准确无误,那么就签发token,在token中,我们可以定义token的签发者、过期时间等等,并返回给前端。注意在签发token时,我们需要定义一个密钥,这个密钥是一个私钥,实际应用中是保密的不可告诉别人。
require 'vendor/autoload.php';use \Firebase\JWT\JWT; define('KEY', '1gHuiop975cdashyex9Ud23ldsvm2Xq'); //密钥$res['result'] = 'failed'; $action = isset($_GET['action']) ? $_GET['action'] : '';if ($action == 'login') { if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = htmlentities($_POST['user']); $password = htmlentities($_POST['pass']); if ($username == 'demo' && $password == 'demo') { //用户名和密码正确,则签发tokon $nowtime = time(); $token = [ 'iss' => 'http://www.helloweba.net', //签发者 'aud' => 'http://www.helloweba.net', //jwt所面向的用户 'iat' => $nowtime, //签发时间 'nbf' => $nowtime + 10, //在什么时间之后该jwt才可用 'exp' => $nowtime + 600, //过期时间-10min 'data' => [ 'userid' => 1, 'username' => $username ] ]; $jwt = JWT::encode($token, KEY); $res['result'] = 'success'; $res['jwt'] = $jwt; } else { $res['msg'] = '用户名或密码错误!'; } } echo json_encode($res); } else { $jwt = isset($_SERVER['HTTP_X_TOKEN']) ? $_SERVER['HTTP_X_TOKEN'] : ''; if (empty($jwt)) { $res['msg'] = 'You do not have permission to access.'; echo json_encode($res); exit; } try { JWT::$leeway = 60; $decoded = JWT::decode($jwt, KEY, ['HS256']); $arr = (array)$decoded; if ($arr['exp'] < time()) { $res['msg'] = '请重新登录'; } else { $res['result'] = 'success'; $res['info'] = $arr; } } catch(Exception $e) { $res['msg'] = 'Token验证失败,请重新登录'; } echo json_encode($res); }