Безопасность

Подсистема безопасности Jmix предоставляет легко настраиваемый механизм контроля доступа для приложений. Она основана на Spring Security и предлагает следующие функции:

  • Интеграция с моделью данных.

    • Разрешения для вызова операций CRUD над сущностями и для просмотра/изменения определенных атрибутов сущностей. Например, пользователь может просматривать документы, но не может создавать, изменять и удалять их, и может просматривать все атрибуты документа, кроме amount.

    • Контроль доступа на уровне строк ограничивает доступ к определенным экземплярам сущности. Например, пользователь может просматривать только те документы, которые были созданы в его отделе.

  • Интеграция с UI.

    • Разрешения для открытия экранов UI и просмотра пунктов главного меню.

    • Если визуальный компонент, такой как TextField, привязан к атрибуту сущности, он автоматически становится доступным только для чтения или скрытым в зависимости от текущих прав пользователя на атрибут. Действия с таблицей отключаются, если пользователю запрещены соответствующие операции CRUD.

  • Декларативное определение ролей и разрешений с использованием аннотированных интерфейсов Java.

  • Возможность определять роли и разрешения во время выполнения и сохранять их в базе данных.

  • UI для просмотра ролей и разрешений, назначения ролей пользователям и создания ролей во время выполнения.

В этом руководстве в основном описывается стандартная реализация подсистемы безопасности. Чтобы использовать все ее функции, убедитесь, что файл build.gradle содержит следующие зависимости:

implementation 'io.jmix.security:jmix-security-starter'
implementation 'io.jmix.security:jmix-security-ui-starter'
implementation 'io.jmix.security:jmix-security-data-starter'

Concepts

Below you can find a few diagrams that explain main concepts of the Jmix security subsystem.

Containers

A container here is a separately runnable/deployable unit that executes code or stores data.

jmix security containers.drawio

In a simple case, Jmix provides all necessary security components (authentication, authorization, users and roles management) in a single application. Users are managed and authenticated by the application.

Optionally, you can use an external identity and access management (IAM) service like OIDC or LDAP. In this case, users are authenticated by the external service, which can also provide the list of roles of the authenticated user back to the application for subsequent authorization.

Users and Roles Management

Roles and policies can be defined in the application both at design time using annotated Java classes, and at runtime using configuration stored in the database.

When users are managed in the application, the administrator creates users and assigns roles to them using the application UI. The User entity is generated by default for a new project.

jmix security admin standard.drawio

If an external IAM service is used, it manages the list of users and usually the list of roles for each user. The administrator also configures roles and policies in the application, and makes sure the application roles match the IAM roles by name. So when a user logs in to the system, the application gets the list of roles assigned to the user by the IAM service and uses its own roles and policies configuration for authorization.

jmix security admin external iam.drawio

There can be also mixed scenarios, when users are created both in IAM service and in the application (for example, automatically upon login).

User Authentication and Authorization

jmix security user.drawio

The authentication mechanism is based on Spring Security. Jmix provides default configuration for Spring Security, as well as the login screen generated in the project and CurrentAuthentication bean for obtainig information about the current user.

When a user works with the application, the access control component of the framework is requested for authorizing user actions. It, in turn, gets the information about the current user permissions from the roles configuration and makes decisions.

Roles and Policies

Below is a diagram that shows relationship between users, roles and policies.

jmix security user roles policies.drawio

A user can have multiple roles of two distinct types: resource and row-level.

Resource roles give users permissions to specific objects and operations, that are denied by default. A user without resource roles has no permissions and cannot access the system.

Row-level roles, in contrast, restrict access to particular entity instances. A user without row-level roles has access to all instances of an entity (if it is permitted by resource roles).

Each role can define policies of different types. Policies specify a target object (a resource for resource permissions, an entity instance or group of instances for row-level policies) and a permission or restriction to apply to this object.

jmix security policy.drawio