By default, in drupal 8 and 9, we will have two types of Authentication Providers. Basically these authentication mechanisms are used to protect the API from security threats.
Both the providers are working in different manner.
Basic Auth: This will work with basic Authorization headers where we need to pass the valid user credentials to access the API.
$.ajax({
url: 'my_drupal/entity/node?_format=json,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa(username:password)
},
data: JSON.stringify(node),
success: function (node) {
// success logic here
}
});Cookie: Ideally, Cookie authorization work in such a way that how an authenticated users access the restricted pages in a browser.
Drupal will carry user session cookie in browsers to identify the users for any actions or access.
When it comes to REST API, it is additionally protected with x-csrf-token. It will verify x-csrf-token against user's session cookie for every API access. So you need to ensure the user is authenticated with the browser / postman (REST client) tool before sending x-csrf-token in headers.
For Headless Drupal approach, the session values should be received from login API success response (headers) and that should be passed as Cookie header along with x-csrf-token like below
$.ajax({
url: 'my_drupal/entity/node?_format=hal_json&foo=bar,
method: 'POST',
headers: {
'Content-Type': 'application/hal+json',
'X-CSRF-Token': csrfToken, // received from my_drupal/session/token
'Cookie': 'SESS0944004040404=ibzSLyhVNhy4tnjfkfgjjg' // current user session cookie
},
data: JSON.stringify(node),
success: function (node) {
// success logic here
}
});There are additional authentication providers can be added using the module Drupal REST & JSON API Authentication
No comments:
Post a Comment