I’m currently working on a frontend project which will feature user logins which will be required to use the application. So far so easy.
I want to use Cockpit’s (v2) user authentication and role management in order to avoid having to code my own login API.
So I’ve just opened my Dev Tools, logged into my Cockpit Backend, and saw that there’s a request going to /auth/check which has a request body like this:
Now I’m wondering where I’m supposed to get the value for the CSRF token from.
As far as I can see, there’s no endpoint which I could use to get a token from Cockpit.
CSRF tokens are meant to identify client sessions and are therefore unique for every session, don’t they?
My question might be stupid - I know. I’m sorry if that’s the case. But I’m not really deep into CSRF and PHP, so this is new to me.
I can see that the Token gets generated within the Csrf Helper at /modules/App/Helper/Csrf.php and used in the Vue login() method in /modules/App/views/auth/login.php
Two simple methods, for Register and Login via API. These are only the basics, how to authenticate. I used the Cockpit internal Methods, only added the Endpoints.
Note: returning the whole user-object is not the best solution, you need to think about a cleanup of this data.
Register
$restApi->addEndPoint('/auth/register', [
/**
* @OA\POST(
* path="/auth/register",
* tags={"auth"},
* @OA\Response(response="200", description="Register via API")
* )
*/
'POST' => function($params, $app) {
$userController = new \System\Controller\Users($app, ['action' => 'user', 'params' => $params]);
error_reporting(0); // there is a, not avoidable, warning in create. to get clean output, disable error reporting
$user = $userController->save();
return $user
},
]);