I’m creating a custom login endpoint to log a user in and send some information back that the regular login endpoint does not. So what I’d like to do is
- Get username and password from request body
- Make request to builtin REST endpoint
user/login
- Parse response to get session data and csrf token and such
- Get some extra user data we want to return with the login response
- Construct together a new body and return
However, I’m having issues using the built-in user/login endpoint and getting the response back in a JSON format
My custom route points to this method:
function login(Request $request) {
$data = Json::decode($request->getContent(), TRUE);
$host = Drupal::request()->getSchemeAndHttpHost();
$url = "$host/user/login";
$req_options = (
'json' => (
'name' => $data('username'),
'pass' => $data('password')
)
);
try {
$response = $client->request('POST', $url, $req_options);
$body = Json::decode($response->getBody());
$success = TRUE;
} catch (RequestException $e) {
$log_error = "User API - Call Endpointnn";
$log_error .= "Request: <pre><code>" . print_r($e->getRequest(), TRUE) . "</code></pre>nn";
$log_error .= "Response: <pre><code>" . print_r($e->getResponse(), TRUE) . "</code></pre>nn";
Drupal::logger('ytp')->error($log_error);
$success = FALSE;
}
// Parse login response to get necessary data and construct custom response
return new JsonResponse($customBody, 200);
}
The issue I’m having is that the response from $response = $client->request('POST', $url, $req_options);
is not a json format, it’s the http page like I just went to the webpage.
If I add this to the $req_options array:
'headers' => (
'Accept' => 'application/json'
'Content-Type' => 'application/hal+json'
)
then I just get an error
GuzzleHttpExceptionClientException: Client error: `POST http://ytplocal.local:8888/user/login` resulted in a `403 Forbidden` response: {"message":"This route can only be accessed by authenticated users."}
which makes absolutely zero sense. If I’m trying to authorize a user via login, how can it only be accessed by authenticated users?
How can I log a user in via REST? It seems like it should be simple, but somehow Drupal has made it incredibly complicated.