I have enabled the Rest and the Basic Auth core modules on a Drupal 10 site, but I am unable to log in using the following code. I keep getting a 403 error.

$drupalUsername = 'myuser';
$drupalPassword = 'mypass';
$drupalApiEndpoint = 'https://mysite.com/user/2'; // Replace with the correct user ID
$authHeader = 'Basic Authentication ' . base64_encode($drupalUsername . ':' . $drupalPassword);
$ch = curl_init($drupalApiEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [$authHeader]);
$response = curl_exec($ch);
echo $response;

Do you have any hint?


Got it working with two small changes!!!

$drupalApiEndpoint = 'https://mysite.com/user/2?_format=json'; // Replace with the correct user ID

$authHeader = 'Authorization: Basic ' . base64_encode($drupalUsername . ':' . $drupalPassword);

1 Answer 1


There are two changes necessary in the code:

  • The endpoint should be 'https://mysite.com/user/login?_format=json'
  • The headers should include the Accept one, which must be set to 'application/json' (*)

If, without being logged in, you try to access a user profile page, which is what happens when the request is for https://mysite.com/user/2, you would get either:

  • a 403 error, if anonymous users are not allowed to access user profiles (The View user information permission is not given to anonymous users.)
  • the user profile, if anonymous users are allowed to access user profiles (The View user information permission is given to anonymous users too.)

Drupal will not redirect from https://mysite.com/user/2 to https://mysite.com/user/login. That would eventually happen when the requested page is https://mysite.com/user.



(*) - Earlier Drupal 8 versions used the Accept header, but that was latter changed (starting from Drupal 8.0.0-beta12). See Accept header based routing got replaced by a query parameter.

  • thx got it working in the end. so ysite.com/user/2 was the actual user that tried to log in! Also had to change Basic Authorization to authHeader = 'Authorization: Basic
    – giorgio79
    Commented Jan 7 at 11:54
  • PS2 it looks like there is no need for a separate login at /user/login with basic auth
    – giorgio79
    Commented Jan 7 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.