Are you looking for a way to create custom permissions for your Drupal 8 module? Since Drupal 8, permissions are defined in a MODULENAME.permissions.yml file.

 create a file in the root directory of your custom module and name it MODULENAME.permissions.yml. Here's an example syntax:

access configuration form:
  title: 'Access the configuration form'
  description: 'Gives permission to access the configuration form'

This will make the permission appear in your /admin/people/permissions. Once you've given this permission to a role, this does not do anything yet. We can now use this permission on a route.

In your MODULENAME.routing.yml:

MODULENAME.settings_form:
  path: '/admin/config/system/mysettings'
  defaults:
    _title: 'Website settings'
    _form: 'Drupal\MODULENAME\Form\SettingsForm'
  requirements:
    _permission: 'access configuration form'

You see that the _permission key holds the exact string as the permission's first key. Clear cache and you will see the user now has access to the page.

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!