1.access_token是登陆后才会有的,这个是用来标记登陆状态,
登陆用户操作会返回access_token
,
2.登陆用户,生成access_token,写入response header 返回
https://github.com/fecshop/yii2_fecshop/blob/master/services/Customer.php#L795
$this->setHeaderAccessToken($identity->access_token);
https://github.com/fecshop/yii2_fecshop/blob/master/services/Customer.php#L878
protected function actionSetHeaderAccessToken($accessToken)
{
if ($accessToken) {
Yii::$app->response->getHeaders()->set('access-token', $accessToken);
return true;
}
}
在用户登陆后就会返回access_token,从header获取
3.access_token的验证
https://github.com/fecshop/yii2_fecshop/blob/master/app/appserver/modules/AppserverTokenController.php#L57
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
# 下面是三种验证access_token方式
//HttpBasicAuth::className(),
//HttpBearerAuth::className(),
# 这是GET参数验证的方式
# http://10.10.10.252:600/user/index/index?access-token=xxxxxxxxxxxxxxxxxxxx
QueryParamAuth::className(),
],
];
https://github.com/fecshop/yii2_fecshop/blob/master/yii/filters/auth/QueryParamAuth.php#L27
public function authenticate($user, $request, $response)
{
$identity = Yii::$service->customer->loginByAccessToken(get_class($this));
if($identity){
return $identity;
}else{
$cors = Yii::$service->helper->appserver->getYiiAuthCors();
if (is_array($cors)) {
foreach ($cors as $c) {
header($c);
}
}
$code = Yii::$service->helper->appserver->account_no_login_or_login_token_timeout;
$result = [ 'code' => $code,'message' => 'token is time out'];
Yii::$app->response->data = $result;
Yii::$app->response->send();
Yii::$app->end();
}
}
https://github.com/fecshop/yii2_fecshop/blob/master/services/Customer.php#L808
/**
* Logs in a user by the given access token.
* Token is passed through headers. So you can get it from the key 'access-token'.
* @param $type
* @return IdentityInterface|null the identity associated with the given access token. Null is returned if
* the access token is invalid.
* @see [[\yii\web\User::loginByAccessToken()]]
*/
protected function actionLoginByAccessToken($type = null)
{
$header = Yii::$app->request->getHeaders();
if (isset($header['access-token']) && $header['access-token']) {
$accessToken = $header['access-token'];
} else {
return null;
}
/** @var \fecshop\models\mysqldb\Customer|null $identity */
$identity = Yii::$app->user->loginByAccessToken($accessToken, $type);
if ($identity !== null) {
$access_token_created_at = $identity->access_token_created_at;
$timeout = Yii::$service->session->timeout;
// 如果时间没有过期,则返回 identity
if ($access_token_created_at + $timeout > time()) {
// 如果时间没有过期,但是快要过期了,在过$updateTimeLimit段时间就要过期,那么更新access_token_created_at。
$updateTimeLimit = Yii::$service->session->updateTimeLimit;
if ($access_token_created_at + $timeout <= (time() + $updateTimeLimit)) {
$identity->access_token_created_at = time();
$identity->save();
}
return $identity;
} else {
$this->logoutByAccessToken();
return null;
}
}
return null;
}