我正在使用this JWTAuth adapter在我的 CakePHP 2.8 应用程序中使用 JWT 身份验证而不是基于 cookie 的身份验证。它工作得很好,除了一个问题:
通常,对于我的 REST 端点之一,我可以使用 $this->Auth->user("id")
来获取当前登录用户的 ID。
当我尝试使用 $this->Auth->allow()
让非成员可以访问 Controller 操作时,出现问题。如果我这样做,在 Controller 中使用 $this->Auth->loggedIn()
会返回 false
,这意味着我无法为登录用户添加额外的逻辑。
使用标准 cookie 身份验证时:
$this->Auth->user('id')
可用于Controller::beforeFilter()
。$this->Auth->loggedIn()
为true
Controller::beforeFilter()
。$this->Auth->user('id')
在 Controller 操作中可用,公共(public) 并且仅限成员(member)。$this->Auth->loggedIn()
在 Controller 操作中为true
,公共(public) 并且仅限成员(member)。
使用 JWT 身份验证时:
$this->Auth->user('id')
在Controller::beforeFilter()
中为null
。$this->Auth->loggedIn()
为false
Controller::beforeFilter()
。$this->Auth->user('id')
在仅限成员的 Controller 操作中可用,null
在公共(public) Controller 操作中可用。$this->Auth->loggedIn()
在仅限成员的 Controller 操作中为true
,在公共(public) Controller 操作中为false
。
有什么方法可以让 Auth 包含 JWTAuth 组件返回的有关 $this->Auth->allow()
公开的操作的信息吗?
此处的示例 Controller :
public function visible(){
// This will always be false, even if a valid JWT token is sent
$this->set("loggedIn", $this->Auth->loggedIn());
}
public function members_only(){
// This will be unavailable if not logged in, and a true if logged in
$this->set("loggedIn", $this->Auth->loggedIn());
}
public function beforeFilter($options = array()){
parent::beforeFilter();
$this->Auth->allow("visible");
}
作为引用,我的 AppController::components 数组;
public $components = array(
'DebugKit.Toolbar',
'Auth' => array(
'authorize' => array(
'Actions' => array(
'actionPath' => 'controllers'
),
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email'),
'contain' => array(
'UserProfile',
)
),
'JwtAuth.JwtToken' => array(
'fields' => array(
'username' => 'email',
'token' => 'password',
),
'header' => 'AuthToken',
'userModel' => 'User',
),
),
'unauthorizedRedirect' => false
),
"Acl",
"RequestHandler",
"Session"
);
最佳答案
对于无状态适配器,身份验证过程在 AuthComponent::startup()
中触发。组件的 startup()
方法在 after Controller::beforeFilter()
运行,这就是为什么 AuthComponent::user()
不返回任何信息。
对于其他适配器,当用户经过身份验证时,身份信息将存储在 session 中。获取该信息不需要任何身份验证过程,这就是 AuthComponent::user()
在基于标准 cookie 的身份验证情况下为您提供用户信息的原因。
关于php - 使用自定义身份验证适配器时检查 CakePHP 上的登录用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534669/