Search code examples
drupal-8drupal-roles

Register new anonymous user with specific role through rest api in Drupal 8


I'm using Drupal 8 rest service to register a new anonymous user and it works fine; the user is created in Drupal.

Then I tried to specify a custom role sending the request below

{
    "name": { "value": "FooBar" },
    "mail": { "value": "[email protected]" },
    "pass": { "value": "secretSauce" },
    "roles": [
        "my_role"
    ]
}

but I receive the error

{
    "message": "Access denied on creating field 'roles'."
}

I checked permissions but I'm not getting what is missing.


Solution

  • An anonymous user cannot assign themselves a role. Drupal automatically assigns a user the role of 'Authenticated user'. You can alter the permissions of that role accordingly if that suits your needs.

    *If you are using the excellent Simple oAuth module to authenticate, then you can also assign the user being created via the REST API a particular 'Scope' (role) based on the consumer ID used when creating the account. On your app you can then create the logic for the particular role to be assigned to a particular user.

    *This all assumes that you are using a headless approach and the users are being created from a JS front-end.

    EDIT

    • Create custom field for Drupal Users
    • Install the Rules Module (https://www.drupal.org/project/rules)
    • Create a rule to act on a new user and assign the appropriate role per the value of the custom field.
    • Pass in the desired value for the custom field from your front end (like your example above)