I'm playing around with the D9 Groups module and I want to test the access control in drush, either using drush php or writing a script and using drush scr.

In drush 8 I would always use drush -u to run as a specific user but that option seems to have disappeared in drush 10.

What's the easiest way to either run drush as a specific user or switch the user in drush php or a script?

Edit: I'm working around this by making calls to json:api endpoints instead but it would still be nice to validate this in drush.

  • I know you're asking for Drush but it's worth noting that the Devel module provides a block for switching users, which can be useful in a local dev environment. Nov 17, 2021 at 15:50
  • Yeah testing in browser is fine, but I specifically need to test at the cli or api level.
    – Lambic
    Nov 17, 2021 at 16:05

1 Answer 1


Hi In your test you could use account switcher service @ core/lib/Drupal/Core/Session/AccountSwitcherInterface.php

For example,

// You can switch to any type of account here.
$this->accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// Using try-catch-finally we make sure we be never leave it by accident.
try {
  // Whatever you want to test
catch (\Exception $e) {
} finally {
  // Making sure we always switch back. Very important if you using u1.

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.