I'd like to Restrict access to Element API endpoint by the current user's group.

Is this possible Using Craft 2?

1 Answer 1


Yes it is you can see here how to check permissions

You can get the current user with

$currentUser = craft()->userSession-getUser();

Then you can check the same conditions like in the example link. If the conditions are false you can return an empty array instead of your endpoints

if(!$currentUser->isInGroup('groupHandle')) {
    return [];

Please make sure to check if the current user is not null

  • Fantastic, thank you. Is there a way to throw an exception too, so that I can warn users who are not able to view the resource? Jun 16, 2018 at 10:02
  • You'll need to throw the exception in your transformer function, however keep in mind exceptions won't be thrown in live mode so the user will be redirected to the homepage instead. The quick and dirty way would be to die() your script out with a message. The clean way would be to create a custom route for each api endpoint and display the message in your controller Jun 16, 2018 at 10:06
  • die('You cannot access this resource') is exactly what I need for this. Thank you !! Jun 16, 2018 at 10:33

Your Answer

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

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