【发布时间】:2019-06-02 03:22:02
【问题描述】:
我在 CakePHP 中使用 JWT auth 来处理 Android 应用程序中的登录操作。我在 Cake 中禁用了 CSRF 保护,并通过“SharedPreferencesConstants”类传递令牌值,其中令牌值是使用下面显示的代码设置的:
// Running default handler
new Handler().post(new Runnable() {
@Override
public void run() {
fcm = new MyFireBaseIntanceIdservice();
String token = fcm.getrefeshtoken();
// Log.e("test", token);
SharedPreferencesConstants.setTOKEN(LoginActivity.this, token);
}
});
不过,我尝试过使用令牌值。
我现在得到的错误是 “错误:[Cake\Http\Exception\InvalidCsrfTokenException] 缺少 CSRF 令牌 cookie”。
目前我尝试过的方法是在 Cake 的 AppController 中禁用 CSRF 保护。
EditText txtEmail = (EditText) findViewById(R.id.txtEmail);
EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
jsonObject.put("email", txtEmail.getText().toString());
jsonObject.put("password", txtPassword.getText().toString());
jsonObject.put("cookieName", "appname");
jsonObject.put("_Token", "_csrfToken");
jsonObject.put("deviceToken", SharedPreferencesConstants.getTOKEN(this));
jsonObject.put("secureKey", SharedPreferencesConstants.getSECUREKEY(this));
我想到的一个计划解决方案与要在请求中传递的 HTTP 标头有关。但是,我找不到任何解决这个想法的方法。
有什么解决方案/建议吗?
编辑#1: 在我的 AppController.php 文件中,我只加载了安全组件,而不是 CSRF。这是相同的代码:
$this->loadComponent('Security');
// $this->loadComponent('Csrf');
而且,我的 CustomersController.php beforeFilter() 函数中的代码是:
$this->getEventManager()->off($this->Csrf);
我在 AppController 中的 JWT 身份验证代码是:
$this->loadComponent('Auth', [
'storage' => 'Memory',
'authenticate' => [
'ADmad/JwtAuth.Jwt' => [
'userModel' => 'Customers',
'fields' => [
'username' => 'email'
],
'parameter' => 'token',
// Boolean indicating whether the "sub" claim of JWT payload
// should be used to query the Users model and get user info.
// If set to `false` JWT's payload is directly returned.
'queryDatasource' => false,
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize',
// If you don't have a login action in your application set
// 'loginAction' to false to prevent getting a MissingRouteException.
'loginAction' => false
],
]);
我希望我添加的新代码可以帮助您更好地了解问题。
【问题讨论】:
-
如果它抱怨 CSRF 令牌 cookie 丢失,这意味着它正在寻找 cookie,这意味着在您的代码中的某处启用了 CSRF 检查。
-
@GregSchmidt 我已经在我的 CustomersController 的 beforeFilter 函数中使用这行代码禁用了它。
$this->eventManager()->off($this->Csrf);如果您对禁用它有任何其他建议,请告诉我。仅供参考:我已经尝试遵循这个 stackoverflow 答案link to answer -
Cake 默认不做任何 CSRF 检查。只有通过添加组件或中间件才能启用此功能。因此,如果它正在检查它,那么这意味着它已在您的代码中的某处启用。也许在你所有的代码中搜索“CSRF”,看看它是不是你以前没有看过的地方?
-
感谢@GregSchmidt!我得到了这个问题的解决方案。我将发布解决方案作为答案。感谢队友的帮助! :)
标签: android cakephp cakephp-3.0 csrf