0

There is a drupal 9 site that has a REST-endpoint that can be accessed for logged-in users (not for anonymous ones).

And, it's necessary to make a GET request to the endpoint using cookie authentication.

Could you clarify, what the correct algorithm of this request is?

I tried to do it two ways.

Way #1.

Send a POST-request to user/login with credentials and get CSRF-token, then use the token in headers of GET-request to my endpoint. No result.

Way #2.

Send a POST-request to user/login with credentials, then send a GET-request to session/token and get token from. After that, use this token from session/token in my GET request.

Also, no result.

In both cases, it returns the 401 error (from Insomnia) or the 403 error (from external JavaScript).

My headers to GET request are

  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': token
  }

The cookie authentication is checked for my REST endpoint in REST UI.

What am I doing wrong?

3
  • If you are checking for cookies, are you passing them back in each request? Is the route enabled for cookie auth? drupal.org/docs/8/core/modules/rest/…
    – Kevin
    Commented Nov 29, 2021 at 14:05
  • Yes, the route is enabled for cookie auth. Here is its description: methods: GET formats: json authentication: basic_auth, cookie About passing cookies back - no, I'm passing tokens. return fetch(calcUrl, { method: 'GET', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token } }) }) Commented Nov 29, 2021 at 14:36
  • Try passing the cookie back as well
    – Clive
    Commented Nov 29, 2021 at 15:26

2 Answers 2

1

When your endpoint requires cookie-auth, you should pass the cookie you get from your login-post with your following GET requests.

CSRF has nothing to do with auth, it's just a CSRF-attack defense.

1

You need to reference the stored cookie. Here's an example using curl:

curl --header "Content-type: application/json" --request POST -s -c cookie.txt --data-binary '{ "name": "username", "pass": "password" }' https://example.com/user/login

From that you will get your cookie in cookie.txt and your token in the json response.

Then you can do a get request like this (get requests don't need a CSRF token):

curl -s -X GET -b cookie.txt --header 'Content-type: application/json' ...

and a post request like this:

curl -s -X POST -b cookie.txt --header 'Content-type: application/json' --header "X-CSRF-Token: $token"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.