Skip to content

3.2. Token authentication

Benji Fisher edited this page Oct 22, 2016 · 2 revisions

To use token authentication, enable the optional RESTful token authentication module.

Configuration options are available in your Drupal site at admin/config/services/restful/token-auth.

The examples below use the command-line curl utility to send GET requests.

ENDPOINTS

  • api/login-token
  • api/refresh-token

REQUEST

Either a session cookie received from a call to api/v1.0/login or with the Drupal user's username and password via HTTP Basic Auth.

Update: with RESTful version 7.x-2.13, the login endpoint is api/login and it returns a CSRF token, not a session cookie. The second method works:

curl -u"USER:PASSWORD" http://www.example.com/api/login-token

You must use the username, not the user ID nor the e-mail address.

RESPONSE

Sample JSON response:

{
  "access_token": "hlckU4t-xTARYuS7RJl8-jkEguSQvaGkracOeY0kL0Q",
  "type": "Bearer",
  "expires_in": 85671,
  "refresh_token": "slnkR0qLCwO9KuGtL_BrRWyMtovEorYjYpWNGymENwk"
}

USING THE ACCESS TOKEN

When requesting a resource that requires token authentication, pass the access token as a query parameter or a custom HTTP header.

$ curl http://www.example.com/api/v1.0/article?access_token=hlckU4t-xTARYuS7RJl8-jkEguSQvaGkracOeY0kL0Q

or

$ curl -H "access-token: hlckU4t-xTARYuS7RJl8-jkEguSQvaGkracOeY0kL0Q" http://www.example.com/api/v1.0/article

The query parameter can be either access_token or access-token, but the custom HTTP header should be access-token.

REFRESH

When the access token expires (by default, the first cron run at least 86400 seconds after it is created) you will get an HTTP 401 response code (Unauthorized) when you try to access restricted resources. This is the same response you get if you do not use the access token at all.

For testing purposes, you can simulate token expiration by deleting the access token:

drush sqlq "delete from restful_token_auth where token='hlckU4t-xTARYuS7RJl8-jkEguSQvaGkracOeY0kL0Q'"

Then (or after the access token has actually expired) you can use the refresh token as part of the URL (not an HTTP header, not a query parameter) to obtain a new access/refresh pair:

curl http://www.example.com/api/refresh-token/slnkR0qLCwO9KuGtL_BrRWyMtovEorYjYpWNGymENwk

with a response in the same format as the sample response above.

Clone this wiki locally