Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
Zewail edited this page Sep 11, 2018 · 1 revision

JWT相关知识大家百度一下吧,网上很多,直接上代码

创建Token

使用 JWT 门面的 attempt 方法来自动验证

namespace app\index\controller;
use app\index\model\User;
use Zewail\Api\Facades\Response;
use Zewail\Api\Facades\JWT;
use Zewail\Api\Exceptions\JWTException;
class Authenticate
{
	public function authenticate()
	{
 // $credentials 可以从请求中获取
 $credentials = ['email'=>'chanzewail@gmail.com', 'password' => '123456'];
 $token = JWT::attempt($credentials);
	}
}

这里使用了 email 和 password 来验证用户是否合法,如果你的用户是通过 mobile或其它字段作为标识,那么可以在 app\index\model\User 模型中,添加 jwtSub 字段:

namespace app\index\model;
use think\Model;
class User extends Model
{
	public $jwtSub = 'mobile';
}

当然,如果你的密码 不是用的 password (绝大多数都用这个,不排除少数奇怪的命名....),那么你可以添加 jwtPassword 字段:

public $jwtPassword = 'strange_password';

这里验证psssword默认使用md5加密,绝大多数情况下这是不够安全的,很多都有自定义的加密方式,那么还有验证密码的方法,添加:

public function jwtEncrypt($password)
{
 	// 只要返回你加密后的结果,会自动比对数据库字段
 	return md5(sha1($password));
}

还可以直接通过用户对象实例创建token

$user = User::get(1);
$token = JWT::fromUser($user);

还可以自定义 Payload 创建任意数据

$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$payload = JWT::makePayload($customClaims);
$token = JWT::encode($payload);

用户认证

要通过http发送一个需要认证通过的请求,需要设置Authorization头

Authorization: Bearer {token}

或者将token信息包含到URL中

http://api.example.com/news?token={token}
解析token

resolveToken方法可以将token还原为payload数组

$payload = JWT::resolveToken();
// ['foo' => 'bar', 'baz' => 'bob']

如果是从user模型创建的token,那么还可以使用authenticate方法,直接验证用户,成功后返回用户模型,失败返回false

if ($user = JWT::authenticate()) {
 // todo
}

当然还有更加手动的方法

// 从请求中获取token
$token = JWT::getToken();
// todo
// 对token进行解码
$payload = JWT::decode($token);

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /