[id='configuring-authorization-programmatically_{context}']
= Programmatically configuring authorization

When using embedded caches, you can configure authorization with the `GlobalSecurityConfigurationBuilder` and `ConfigurationBuilder` classes.

.Procedure

. Construct a `GlobalConfigurationBuilder` that enables authorization, specifies a role mapper, and defines a set of roles and permissions.
+
[source,java]
----
GlobalConfigurationBuilder global = new GlobalConfigurationBuilder();
global
   .security()
      .authorization().enable() <1>
         .principalRoleMapper(new IdentityRoleMapper()) <2>
         .role("admin") <3>
            .permission(AuthorizationPermission.ALL)
         .role("reader")
            .permission(AuthorizationPermission.READ)
         .role("writer")
            .permission(AuthorizationPermission.WRITE)
         .role("supervisor")
            .permission(AuthorizationPermission.READ)
            .permission(AuthorizationPermission.WRITE)
            .permission(AuthorizationPermission.EXEC);
----
+
<1> Enables {brandname} authorization for the Cache Manager.
<2> Specifies an implementation of `PrincipalRoleMapper` that maps Principals
to roles.
<3> Defines roles and their associated permissions.
+
. Enable authorization in the `ConfigurationBuilder` for caches to restrict access based on user roles.
+
----
ConfigurationBuilder config = new ConfigurationBuilder();
config
   .security()
      .authorization()
         .enable(); <1>
----
+
<1> Implicitly adds all roles from the global configuration.
+
If you do not want to apply all roles to a cache, explicitly define the roles
that are authorized for caches as follows:
+
----
ConfigurationBuilder config = new ConfigurationBuilder();
config
   .security()
      .authorization()
         .enable()
         .role("admin") <1>
         .role("supervisor")
         .role("reader");
----
+
<1> Defines authorized roles for the cache. In this example, users who have the `writer` role only are not authorized for the "secured" cache. {brandname} denies any access requests from those users.

[role="_additional-resources"]
.Additional resources
* link:{javadocroot}/org/infinispan/configuration/global/GlobalSecurityConfigurationBuilder.html[org.infinispan.configuration.global.GlobalSecurityConfigurationBuilder]
* link:{javadocroot}/org/infinispan/configuration/cache/ConfigurationBuilder.html[org.infinispan.configuration.cache.ConfigurationBuilder]
