User login REST API in drupal8

  0 comments

To use login API in drupal first you have to get CSRF Token. This token will use in login API.

There is API to get CSRF TOKEN in drupal8. It doesn’t need any module installation or configuration from drupal end.

CSRF TOKEN API DETAIL

	GET: http://XXXXXX.org/session/token

CURL COMMAND:

curl -X GET -k -i 'https://XXXXXX.org/session/token'

JAVASCRIPT CODE:

 

   fetch('/session/token')
     .then(function(response) {
       return response;
     })
     .then(function(token) {
       console.log('CSRF TOKEN'+token);
     });

RESPONSE:

	Gxfoibl-emxsbQ6xtBuRGrRWqZKzp_mnQmJACVsjKQs

 

Now you will need to install "RESTful Web Services" Module. That is default included in drupal8.

Now go on to this link /admin/config/services/rest and enable user entity API. GET method must be enable. You can take a look on below screenshot.

REST

REST

Login API Detail:

	END POINT:/user/login?_format=json
	Content-Type:application/json
    method:POST
	Data: { "name": "admin", "pass": "myPassword" }    

CURL COMMAND:

curl -X POST -k -H 'Content-Type: application/json' -H 'X-Csrf-Token: Gxfoibl-emxsbQ6xtBuRGrRWqZKzp_mnQmJACVsjKQs' -i 'https://drupalchamp.org/user/login?_format=json' --data '{ "name": "name", "pass": "pass" } '

JAVASCRIPT CODE:

		fetch('/user/login?_format=json', {
			  method: 'POST',
			  headers: {
				'Content-Type': 'application/json',
				'X-CSRF-Token': csrfToken
			  },
			  body: JSON.stringify({
				'name':username,
				'pass' : password,
			  }),
			})
			.then(response => response.json())
			.then(data =>{
				console.log('sddddsuccess', data);
			  }
			);

RESPONSE:

{"current_user":{"uid":"145","name":"test"},"csrf_token":"POAp3fa3HQD3bfOR_wvoflVva07OvIbocw6FIbHABNY","logout_token":"aBYL4-ltfO0yuyzrm2AckWIgyUGN0g1TZYl56mrgaf0"}

Add new comment