In the previous article, the Spring Boot application integrated with Keycloak realizes unified authentication and permission control. The part of permission control is judged by Role directly, which is also sufficient for simple systems. However, for complex systems that need to integrate fine-grained permission control, it is obviously inappropriate to simply rely on Role’s direct control, and the application itself is not flexible in the way of direct coupling with Role. This article describes how Spring Boot’s Web application integrates Keycloak for fine-grained permission control.

Keycloak core permissions concept overview

Keycloak supports fine-grained permission control policies and can combine the following access control mechanisms:

  • Attribute-based access control (ABAC)
  • Role-based access control (RBAC)
  • User-based access control (UBAC)
  • Context-based access control (CBAC)
  • Rule-based access control
  • Time-based access control

Keycloak authorization process

There are three main processes to understand if you want to use fine-grained permission control at Keycloak:

  • Resoucre Management
  • Permission and Policy Management
  • Policy Enforcement

Resource management

Resource management is mainly used to define which objects of the resource server need to be protected

The relationship among resource service, resource and Scope is as follows:

Permission and Policy Management

A policy defines which conditions are met to access a resource, but the policy itself is not associated with the resource. To enable policies to apply to corresponding resources, you need to configure permissions and associate the resources to be protected with policies.

Policy enforcement

Policy execution requires the integration of a Policy Enforcement Point (PEP) within the resource service to communicate with the Keycloak service to obtain permissions, etc., to determine which resources can be accessed.

Keycloak Fine-grained permission control background configuration

To enable fine-grained permission control at Keycloak, you need to create the appropriate client and enable the authorization service. Configure resource management, permission management, and policy management based on the authorization process. This document simulates the following scenarios to better understand the configuration.

The scenario is as follows:

  • The applications that need to be protected are/admin,/customer/view,/customer/deleteThree main resources
  • haveROLE_ADMINUsers of the role have access to all resources
  • haveROLE_CUSTOMERUsers of the role can access only/customer/viewOther resources cannot be accessed

Let’s take a look at the setup behind Keycloak for the scenario above.

Create roles and users

  1. Create three roles. ROLE_USER is bound to all users

  2. Create two users and bind them to roles

Create a client and enable the authorization service

  1. Creating a Client

  2. Set the Confidential access type and enable authorization

Configure resources, policies, and permissions

Under the Authorization Tab of the client, there are many sub-tabs to configure resources, policies, and permissions.

Settings TAB configuration

Under the Settings TAB are some of the global default configurations for authorization

Here are two important Settings under Settings

  • Policy Enforcement Mode: Specifies how the Policy is executed when the authorization server receives the request

    • Enforcing: Requests are denied access by default if no policy is associated with the resource, which is also the default option
    • Permissive: Allows access to a resource when no associated policy is configured
    • Disabled: Disables all access policies for all resources
  • Decision Strategy: Represents how permissions are ultimately calculated to determine whether the appropriate resource can be authorized or not

    • Affirmative: At least one privilege calculation makes positive decisions
    • Unanimous: All permission calculations need a forward decision

Resources TAB configuration

The Resoucres TAB is used to configure the resources that need to be protected. The following resources are configured in this example. Note the Scopes Settings

Authorization Scopes TAB configuration

Policies TAB configuration

The configured Policies are used to associate resources with permission Settings. Keycloak supports many Policies. For details about the Policies, see the official documents

Permissions TAB configuration

Permission is used to configure resources and how policies are associated, and the Decision Strategy adopted when there are multiple policy associations ultimately determines whether resources can be authorized. The configuration item of Decision Strategy has the same meaning as the Settings above. I will not repeat it here

The Spring Boot project integrates Keycloak code configuration examples

Application. Yml Keycloak configuration

keycloak:
  realm: demo
  auth-server-url: http://127.0.0.1:8080/auth
  resource: spring-boot-authz-keycloak-web
  ssl-required: external
  credentials:
    secret: dede7fd6-2817-491c-b7e5-27f65bbb5fc7
  use-resource-role-mappings: false
  bearer-only: false
  autodetect-bearer-only: false
  security-constraints:
    - authRoles:
        - ROLE_USER
      securityCollections:
        - name: all
          patterns:
            - / *
  policy-enforcer-config:
    on-deny-redirect-to: /accessDenied
Copy the code

For details about the configuration file, see the previous article. The policy-enforcer-config configuration item indicates that fine-grained permission control is enabled for the current application. On-deny-redirect-to indicates the address to redirect to when access is denied

Controller sample code

@RequestMapping(value = "/customer/view", method = {RequestMethod.GET})
public String customerView(Model model, HttpServletRequest request) {
    KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    model.addAttribute("authz", keycloak.getAuthorizationContext());
    return "customer/view";
}

@RequestMapping(value = "/customer/delete", method = {RequestMethod.GET, RequestMethod.POST})
public String customerDelete(Model model, HttpServletRequest request) {
    KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    model.addAttribute("authz", keycloak.getAuthorizationContext());
    return "customer/delete";
}

@RequestMapping(value = "/admin", method = {RequestMethod.GET, RequestMethod.POST})
public String admin(Model model, HttpServletRequest request) {
    KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    model.addAttribute("authz", keycloak.getAuthorizationContext());
    return "admin/view";
}

@RequestMapping(value = "/admin/delete", method = {RequestMethod.GET, RequestMethod.POST})
public String adminDelete(Model model, HttpServletRequest request) {
    KeycloakSecurityContext keycloak = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    model.addAttribute("authz", keycloak.getAuthorizationContext());
    return "admin/delete";
}

@RequestMapping(value = "/accessDenied", method = {RequestMethod.GET, RequestMethod.POST})
public String accessDenied(a) {
    return "access_denied";
}
Copy the code

The example Controller basically passes the Keycloak authorization context to the Model and specifies the corresponding view rendering

Sample code for the Customer /view.ftl page

<h1>Customer View</h1>
<div>
    <#if authz.hasScopePermission("delete")>
        <a href="/customer/delete">delete</a>
    </#if>
</div>
Copy the code

Pages using freemarker are simpler, but other view engines can also be used. Here is a sample code for this page, and only those with delete Scope permission can see the Delete link

Project effect Demonstration

Customer User access effect

When you visit the/Customer /view page, you cannot see the DELETE link

Access the/CUSTOME /delete and /admin pages and directly jump to the /accessDenied page

Admin user access effect

The admin user visits the/Customer /view page and sees the delete link

If the admin user clicks the delete link or directly visits /customer/delete, the page can be displayed normally

The admin user can access the /admin page

conclusion

This article briefly introduces the concept of fine-grained permission for Keycloak, and shows how to configure the Keycloak background and Spring Boot Web type applications to achieve fine-grained permission control in a simple simulation scenario. Keycloak is flexible for fine-grained perm-related policies. You can select or even combine multiple policies based on actual scenarios.

This article sample project code: spring-boot-Authz-keycloak -web