How to authenticate API requests with 2FA?

After enabling 2FA, I get “Basic authentication cannot be used with 2FA” when doing a POST request to a API route defined in a plugin. If I set ‘basicAuth’ => false I get “Unauthenticated” instead.

Authentication is a bit of a strange territory for me, so help is appreciated.

The request is called internally, so it is not from a remote if that makes a difference.

Only with a particular user for which 2FA is enabled, or just because 2FA is enabled in config?

I have it enabled in my config. The user I authenticate with in the api request is my admin user and I have completed the setup with 2FA codes etc via the panel for it. Is there another way?

  'api' => [
      'basicAuth' => true 
  ],
  'auth' => [
      'methods' => [
          'password' => ['2fa' => true]
      ],
  ],

What if you create another “apiuser” for basic auth, for whom you do not set up 2FA?

How do I do that? :slight_smile: Didn’t know you can set different auth methods per user

No, you can’t. But there are 2 steps to enabling 2FA for a user. 1. the option in config 2. The setup for the user in the user account. That’s why I asked if you had only done step 1, or step 1 and 2 for the user you are using for basic auth.

If you have just done step 1, and cannot access the api with basic auth, then I don’t have a solution, apart from using session based auth instead of basic auth.

WIll absolutely try that and report back!
I remember reading something about that the api require basic auth?

I created a new admin user in the panel, without doing the second step, and used it’s credentials in the request. Still the same error. It only works if I change 2fa to false in the config.

If you have just done step 1, and cannot access the api with basic auth, then I don’t have a solution, apart from using session based auth instead of basic auth.

@texnixe, I need to make the request from the backend. Is it possible to use session based auth from the backend? The docs is a bit ambivalent on this:

Sessions also require a correct session cookie for every request. Therefore, session-based authentication works best when you make API calls from the frontend of the same site/domain.
Authentication | Kirby CMS

“Works best” gives me a slight hope :smile: Do you have any examples on how such a request can be done? Or if it indeed is not possible to make API requests from the backend with 2FA enabled, then perhaps I should open be an issue on GitHub?