2

I'm working on web app with a Drupal 8 back-end which is accessed by the D8 REST API. I need to get the current user role so I can manage some options by role. Is there an existing REST route for getting the role and/or ID of the currently authenticated user. I've had success with other REST routes like http://example.com/drupal/user/1?_format=hal_json, but this returns the user with id=1. What i'd like is http://example.com/cms/user/me?_format=hal_json

Any suggestions?

1

3 Answers 3

3

I have just used views to get this working.

  1. Duplicate the default people view and rename it current_user.
  2. Add a rest export route eg. rest/users/current_user.
  3. Add a filter for current user. (User: Current = yes)
  4. Save all.
  5. Retrieve the current user via http get request on example.com/rest/user/current_user?_format=hal_json

Thanks to QueenVictoria for the advice.

0
1

I've used Views to do this as you can customise your permissions, path and fields. Roles aren't available on the native ReST path to anonymous users.

For example here is the role stanza for user 200 when logged in as user 1. This is missing when logged out. I presume that is a factor of

roles: [
  {
    target_id: "student"
  }
],

BTW isn't the default ReST path user/200?_format=hal_json?

0
0

The JSON API entrypoint contains data about the currently logged in user in meta.links.me. The core JSON API module needs to be enabled. The key meta.links.me won't exist for anonymous users. Visit /jsonapi, and get more information about the current user from the link at meta.links.me.href. Example output from /jsonapi:

{
  "jsonapi": {
    "version": "1.0",
    "meta": {
      "links": {
        "self": {
          "href": "http://jsonapi.org/format/1.0/"
        }
      }
    }
  },
  "data": [
    
  ],
  "meta": {
    "links": {
      "me": {
        "meta": {
          "id": "ba4f782f-2c5d-4280-8897-9e883f36711c"
        },
        "href": "https://example.com/jsonapi/user/user/ba4f782f-2c5d-4280-8897-9e883f36711c"
      }
    }
  }
}

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.