craftcms / craftcms/cms

[5.x]: Headless sign in

Open
#16,259 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
PHP
Stars
3.6k
Forks
705
Avg merge
1d 5h
Merged PRs (30d)
134

Description

What happened?
Description

I'm trying to set up authentication with Craft Users within a Nextjs frontend using next-auth, but unable to do so. Whenever a user fills in the login form, a request goes to an api-route in Next (using the Next-auth credentials provider), which from there I'll send a request to Crafts' login action: process.env.NEXT_PUBLIC_API_URL + '/actions/users/login'

Whenever I try to do this fetch from the API route I get an CSRF issue (the unable to verify error). When I test this request from the frontend directly (instead of going through the API route) I get a proper response from /actions/users/login (f.ex. invalid_credentials if wrong username/pw).

That made me think, is the CRAFT_CSRF_TOKEN cookie not present in the request to Craft from the API route or what's going on. Turns out the cookie was not sent to the api route, but after changing the defaultCookieDomain to include subdomains I could see the CRAFT_CSRF_TOKEN cookie in the request data in the API route.

I get the CRAFT_CSRF_TOKEN from the actions/users/session-info action, and it's setting the cookie and adding the csrfTokenValue field in the form which I send in the X-CSRF-Token in the API-route.

The current code looks like this:

const res = await fetch(
          process.env.NEXT_PUBLIC_API_URL + '/actions/users/login',
          {
            method: 'POST',
            body: data,
            credentials: 'include',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json',
              'X-Requested-With': 'XMLHttpRequest',
              'X-CSRF-Token': form.csrfTokenValue
            },
          }
        );

But this is not working with the unable to verify error.

I also setting the cookie key in the headers object manually to request.headers.cookie like so cookie: request.headers.cookie to see if I could forward the cookies to Craft since it seems it's not included.

Is there something I'm missing here, or is it not possible to users/login action from another server on another subdomain?

The craft url is: https://craft.lndo.site
The nextjs site domain is: https://internal.craft.lndo.site

This is the response I get from the query:

 {
  name: 'Bad Request',
  message: 'Kunne ikke verifisere innsendt data.',
  code: 0,
  status: 400,
  exception: 'yii\\web\\BadRequestHttpException',
  file: '/app/backend/vendor/yiisoft/yii2/web/Controller.php',
  line: 221,
  trace: [
    {
      file: '/app/backend/vendor/craftcms/cms/src/web/Controller.php',
      line: 176,
      function: 'beforeAction',
      class: 'yii\\web\\Controller',
      type: '->'
    },
    {
      file: '/app/backend/vendor/craftcms/cms/src/controllers/UsersController.php',
      line: 192,
      function: 'beforeAction',
      class: 'craft\\web\\Controller',
      type: '->'
    },
    {
      file: '/app/backend/vendor/yiisoft/yii2/base/Controller.php',
      line: 176,
      function: 'beforeAction',
      class: 'craft\\controllers\\UsersController',
      type: '->'
    },
    {
      file: '/app/backend/vendor/yiisoft/yii2/base/Module.php',
      line: 552,
      function: 'runAction',
      class: 'yii\\base\\Controller',
      type: '->'
    },
    {
      file: '/app/backend/vendor/craftcms/cms/src/web/Application.php',
      line: 350,
      function: 'runAction',
      class: 'yii\\base\\Module',
      type: '->'
    },
    {
      file: '/app/backend/vendor/craftcms/cms/src/web/Application.php',
      line: 649,
      function: 'runAction',
      class: 'craft\\web\\Application',
      type: '->'
    },
    {
      file: '/app/backend/vendor/craftcms/cms/src/web/Application.php',
      line: 312,
      function: '_processActionRequest',
      class: 'craft\\web\\Application',
      type: '->'
    },
    {
      file: '/app/backend/vendor/yiisoft/yii2/base/Application.php',
      line: 384,
      function: 'handleRequest',
      class: 'craft\\web\\Application',
      type: '->'
    },
    {
      file: '/app/backend/web/index.php',
      line: 12,
      function: 'run',
      class: 'yii\\base\\Application',
      type: '->'
    }
  ]
}
Steps to reproduce
  1. Run Craft in headless and run the request from an api-endpoint in another subdomain
Expected behavior

I'd expect the csrf header token and cookie token to match, and let my request through.

Actual behavior

I'm stopped by csrf.

Craft CMS version

5.5.3

PHP version

8.2

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Craft actions/users/session-info and actions/users/login endpoints, then compare the CSRF cookie and header forwarding from the Next.js API route. Review the request path shown through craftcms/cms/src/controllers/UsersController.php and the Yii controller; done means the cross-subdomain login request passes CSRF verification.

Written by the indexing model from the issue text.

Assessment

Tech stack
nextjs, php
Domain
api, authentication
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.