Drupal 8 core contains two methods of authenticating a user when making an API request:
- Basic authentication: The username and password of a valid account are passed in the request header. Note that this does not create a session in Drupal. The REST module is able to check permissions for operations, but other modules that expect to have a valid user session will not work as intended. This includes Views, so any Views that check either roles or permissions will fail with a 403 Forbidden response when using HTTP authentication.
- Cookies: The user session cookie is passed with the request in the same way that a normal page request would be. If the application using the REST API relies on the user logging in using the normal /user/login process, this will work without any changes. If the REST client needs to do so directly, it can make a POST request to /user/login?_format=json and pass the username and password as a JSON object like {name: "name", "pass": "password"}. If successful, the response will contain information about the user as well as the CSRF token to use for all authenticated requests. For example:
{
"current_user": {
"uid": 1,
"roles": ["authenticated"],
"name": "username"
},
"csrf_token": "abc123",
"logout_token": "def123"
}
When logging out, the logout token must be sent in the GET request. For example, /user/logout?_format=json&token=def123. The application will need to keep track of the logout_token because any attempt to login again with the same credentials will return a 403 Forbidden until either a successful logout request is sent or the session expires or is deleted.