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. or you can use mymodule_entity_presave to assign role to the anonymous users.
use Drupal\Core\Entity\EntityInterface;
function mymodule_entity_presave(EntityInterface $entity)
{
if ($entity->getEntityTypeId() == 'user') {
$role = $entity->get('field_role')->value;
if ($role) {
$entity->addRole($role);
}elseif ($role = \Drupal::request()->headers->get("role")) {
$entity->addRole($role);
}
}
}
Example 1: add role to body
{
"name": { "value": "fooBar" },
"mail": { "value": "foo@bar.com" },
"pass": { "value": "secretSauce" },
"field_role": { "value": "editor" }
}
Example 1: add role to header
Content-type: application/json
role: editor