CakePHP 3 REST ajax login with React


#1

I am building rest API. How to make ajax login and get CSRF token.

// In middelware

->add(function($request, $response, $next) {
                    return $next($request, $response)
                            ->withHeader('Access-Control-Allow-Origin', '*')
                            ->withHeader('Access-Control-Allow-Methods', '*')
                            ->withHeader('Access-Control-Allow-Credentials', 'true')
                            ->withHeader('Access-Control-Allow-Headers', '*')
//                            ->withHeader('Access-Control-Allow-Headers', 'X-CSRF-Token')
                            ->withHeader('Access-Control-Allow-Type', 'application/json');
                });

When i send post request then appear cors error

POST http://localhost/spot/api/users.json 403 (Forbidden)
:4000/#/login:1 Failed to load http://localhost/spot/api/users.json: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:4000’ is therefore not allowed access. The response had HTTP status code 403.


#2

One the good way is to use JsonWebToken authentication (cake plugin) to build a rest API.

Regarding the CSRF, you should use the middleware for that :wink:


#3

I wondering how to get first time csrf token in login. After write token to cookie everything fine.