API Key Authentication

Last updated on
20 February 2024

API Key Authentication is one of the simplest methods to protect Drupal REST APIs. Once you have generated API Keys for all your users, you can then use those keys to secure access to your Drupal REST APIs .

You can do so by sending the user’s Drupal username and API key in the Authorization header of your every API request. The Drupal REST & JSON API Authentication module will then authenticate the request based on the username and corresponding API key. 

 Download  Know more

Setup Video:

 Drupal REST API Key Authentication Youtube Video

Pre-requisites: Download and Installation:

  • Download & install the Drupal REST & JSON API Authentication module.
  • REST UI: This module provides you with a user interface for configuring the REST module. 
  • Enable the following Web Services modules from under the Extend section(/admin/modules) of your Drupal site:
    • REST UI
    • RESTful Web Services
    • Serialization

    drupal rest api enable module

Steps to setup API Key based Authentication in Drupal:

  • For better understanding, we will be taking an example of adding API Key-based authentication to the Create User API for Drupal.
  • Please note that the /entity/user API of Drupal is used to create a user in Drupal.

Enable the API and assign methods and operations as follows:

  • The first step is to enable the API and also assign methods and operations allowed on that particular API. This can be done using the REST UI module or you can simply modify the config.
  • To enable the API using the REST UI module, click on the Configure button of the REST UI module(as shown below)

    drupal rest api configre UI module

  • Considering our example, we have to enable the /entity/user API. Enable this API using the Enable option in front of it.

    drupal rest api enable user node

  • Now, as our goal is to create a user in drupal, select the following configs:
    • Method: POST
    • Format: json
    • Authentication provider: rest_api_authentication.
  • Selecting rest_api_authentication will allow the miniOrange REST API Authentication module to authenticate your /entity/user API. Click on the Save Configuration button to continue.

    drupal rest api select method and formats

Create an API Key user field in Drupal:

Note: If you are using free version of the module you can skip this step.

In this step, we will set up how the API key is used to authenticate the API calls. In order to do so, first we need to create a User Attribute field for storing an API key.

  • Navigate to the manage field (/admin/config/people/accounts/fields) tab of Drupal.
  • To add the field, click on the Add field button.

    drupal rest api manage feilds

  • Now from the Add a new field dropdown, select the Text (Plain) option and enter API Key in the label textfield. Now, click on the Save and continue button to save your settings.
  • Please ensure that the machine name of the user attribute should be field_api_key.

    drupal rest api add new feild

  • Now proceed with clicking on the Save field settings and then on the Save Settings button to complete the field creation.

    drupal save fields

    drupal rest api key settings

  • You can now see an additional API Key textfield present in your user profile.

Setup API Key based Authentication:

  • In this step, we will generate an API Key,  in order to do so please navigate to the API Authentication tab of the REST API Authentication Module. (/admin/config/people/rest_api_authentication/auth_settings)
  • Select the Enable Authentication checkbox and click on Save Settings.
  • For enabling the API Key-Based Authentication, select the API Key radio button.
  • In the same screen, you can generate the API key for a particular user or you can generate the API key for all the users at once.
  • Right now we will generate the API key for a single user only.
  • In the Enter username text field, enter the username for which you want to generate the API key and click on the Generate API key for this user button.
  • You can now view the generated API Key from the API Key field of your user profile.

    drupal api create key

  • Keep the API key handy as it will be used later while authenticating the API.

Grant Drupal roles permission to create a user in Drupal:

  • If you require, you can also grant non-admin Drupal roles permission to create a user in Drupal. You can do so by assigning Drupal roles to the Administer users permission from under the permission section (/admin/people/permissions) of your Drupal site.

    drupal rest api admin userinfo

That’s it!!!

  • Now let’s try to create a user in Drupal through an API call using an API key for authentication.

Example:

  • To create a user in Drupal you have to make a POST request along with the username of the user and API key issued by the miniOrange REST API Authentication Module. The value of the username and API key must be in base64encoded format.  You can refer to the below format to make a call.

    Request: POST  <your_drupal_base_url>/entity/user?_format=json
    Header: Authorization: Basic base64encoded <username:api_key>
                 Accept: application/json
                 Content-Type: application/json

    Body: {
                "name": [
                            {"value": "<username>"}
                    ],
               "mail": [
                            {"value": "<email>"}
                    ],
                "pass":[
                            {"value": "<password>"}
                    ],
                "status":[
                            {"value": "1"}
                    ]
    }

    CURL Request Format-

    curl --location --request POST  ‘<your_drupal_base_url>/entity/user?_format=json' \
    --header 'Accept: application/json' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Basic base64encoded<username:API key>’ \
    --data-raw '   {
        "name": [
            {"value": "Username"}
        ],
        "mail": [
            {"value": "email"}
        ],
        "pass":[
            {"value": "Password"}
        ],
        "status":[
            {"value": "1"}
        ]
    }'

  • You can also refer to the image of the Postman request added below: 

    drupal rest api request for postman

  • A successful response returns the user information that you have created. (please refer to the image below)

    drupal rest api response for postman

  • If you receive any error in the response, you can refer to the below table for the error description and possible solutions.

Error Response:

Error Description
MISSING_AUTHORIZATION_HEADER

You will get this error whenever you don't send an Authorization Header in the API request or if it was removed by your server due to some reasons.

Example:
{
  "status": "error",
  "error": "MISSING_AUTHORIZATION_HEADER",
  "error_description": "Authorization header not received."
}

INVALID_AUTHORIZATION_HEADER_TOKEN_TYPE You will get this error when you send the Authorization header but in a valid format.
Example:
{
  "status": "error",
  "error": "INVALID_AUTHORIZATION_HEADER_TOKEN_TYPE",
  "error_description": "Authorization header must be the type of Basic Authentication."
}
USER_DOES_NOT_EXIST

You will get this error whenever the module does not find any account belonging to the username that you have sent in the request.

Example:
{
  "status": "error",
  "error": "USER_DOES_NOT_EXIST",
  "error_description": "The user does not exist."
}

INVALID_API_KEY

You will get this error whenever the API key sent in the API call does not match.

Example:
{
  "status": "error",
  "error": "INVALID_API_KEY",
  "error_description": "The API Key sent in the Request seems to be invalid or incorrect using invalid API Key."
}

USER_NAME_MISSING

You will get this error whenever the module is not able to find the username in the API call.

Example:
{
  "status": "error",
  "error": "USER_NAME_MISSING",
  "error_description": "The username is missing from the request"
}

INVALID_AUTHORIZATION_HEADER

You will get this error whenever the module is not able to decode the header properly or not found the username and API key in the header.

Example:
{
  "status": "error",
  "error": "INVALID_AUTHORIZATION_HEADER",
  "error_description": "The authorization header seems to be invalid"
}

Congratulations!!!! You can now authenticate any calls to your Drupal APIs using API Key-Based Authentication method.

We hope you found this document useful and informative.

Contact our 24*7 support team

Feel free to reach out to our Drupal experts if you need any sort of assistance in setting up REST & JSON API Authentication on your Drupal site.   

 Get In Touch With Us Join Our Slack Channel

back to top Back to top  

Help improve this page

Page status: No known problems

You can: