1

I am trying to login via an Ajax request. I don't need any fancy REST features, I just want to login. According to the docs and other questions here it should be pretty straightforward for Drupal 8.3.7:

 $.ajax({
    method: "POST",
    url: "/user/login?_format=json",
    dataType: "json",
    contentType: "application/json",
    data: { user: "myname", pass: "mypass" }
})

However, this doesn't work at all for me, as I always get a 403 forbidden response. The funny thing is, I can get it to work in Postman (a third party tool for sending REST requests) but only under certain conditions. It works great in Postman as long as I don't submit the domain's cookie with the request. If I stick to the default settings and let it send the cookie I have the '403 forbidden' issues again. If I then manually delete the cookie all is well again for the next attempt (then it sets a new cookie and the next attempt will fail).

I assume I am having the same problem with the in-browser jQuery version of my request, but there I can not seem to get rid of the cookie so I can't get it to work. I have tried every answer provided in related questions (csrf token, jdrupal, basic auth, ...) but it's always the same issue if I make a request where cookie data is automatically attached by the browser.

Any ideas what is going wrong? Why is Drupal hating on the cookie data (which was set by Drupal itself!). Can authenticated users not use the login url anymore? Is it maybe because the /user/login page redirects to /user for authenticated users, so the request is sent to /user instead if you're already authenticated?

  • 1
    If you have the cookie, you are already logged in, so login is denied. Simple as that. – Alfred Armstrong Sep 12 '17 at 12:38
  • 1
    You are right. I was stressing out over nothing. It's as simple as that. Manually logging out deletes the cookie and it works fine again. So the issue was that I was testing my code while I was already logged in in the GUI. Thanks for pointing it out :) – peanutman Sep 12 '17 at 13:01
2

Can authenticated users not use the login url anymore?

No they can't, it wouldn't make sense for them to be able to (you can't login if you're already logged in).

In practical terms, this is the routing entry for the login endpoint:

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

As you can see from the requirements, the user cannot already be logged in to access the resource.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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