来自Android应用程序的cakephp JWT身份验证的令牌值应该是多少?

时间:2019-06-02 03:22:03

标签: android cakephp cakephp-3.0 csrf

我在CakePHP中使用JWT身份验证来处理Android App中的登录操作。我已禁用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 Auth代码是:

    $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
        ],
    ]);

我希望我添加的新代码可以帮助您更好地了解问题。

1 个答案:

答案 0 :(得分:0)

我得到了这个问题的答案。并且,所有感谢归功于@GregSchmidt。是因为他的好建议。所以,这就是我所做的。

在我的routes.php文件的config文件夹下几乎没有几行代码,我一直都在注释。下面是代码行:

$routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
    'httpOnly' => true
]));

还有

$routes->applyMiddleware('csrf');

最后,我从控制器中删除了所有禁用Csrf的代码,魔术终于发生了。 :)