Начало работы с REST

В этом разделе представлен пример получения через REST API информации о пользователях приложения.

Для начала добавьте REST в свой проект как описано в разделе Установка.

Получение токена доступа

In order to access the protected resource the client must present a valid access token. The OAuth 2.1 specification provides several ways to get an access token from the authorization server. They are called grant types. In this example we will use the Client Credentials grant which is suitable for confidential clients, such as backend integrations.

The idea is that in Jmix application we must register the client (e.g. an external application that needs to access Jmix REST API), define client id and secret, and then using these credentials we will be able to get the access token by a special HTTP request.

Functionality responsible for issuing tokens and supporting all OAuth 2.1 and OpenID Connect 1.0 protocol features are located inside the Authorization Server addon that must have been already included during the installation of the REST API add-on (io.jmix.authserver:jmix-authserver-starter). The Authorization Server add-on is built on top of Spring Authorization Server.

The simplest way to register a client is to add standard Spring Authorization Server application properties:

# The client id is my-client
spring.security.oauth2.authorizationserver.client.myclient.registration.client-id=my-client
# The client secret (password) is my-secret
spring.security.oauth2.authorizationserver.client.myclient.registration.client-secret={noop}my-secret
# Enable Client Credential grant for the my-client
spring.security.oauth2.authorizationserver.client.myclient.registration.authorization-grant-types=client_credentials
# Client credentials must be passed in the Authorization header using the HTTP Basic authentication scheme
spring.security.oauth2.authorizationserver.client.myclient.registration.client-authentication_methods=client_secret_basic
# Use opaque tokens instead of JWT
spring.security.oauth2.authorizationserver.client.myclient.token.access-token-format=reference

The next set of application properties is Jmix-specific and defines which resource and row-level roles must be assigned to the access token issued to the client. In this example we will assign two resource roles:

  • rest-minimal (REST: minimal access) - to enable REST API endpoints access.

  • user-management (User management) - to allow operations with the User entity using REST API.

# my-client is the client id we configured previously
jmix.authserver.client.myclient.client-id = my-client
jmix.authserver.client.myclient.resource-roles = user-management, rest-minimal

The user-management role looks as follows:

@ResourceRole(name = "User management", code = UserManagementRole.CODE, scope = "API") (1)
public interface UserManagementRole {

    String CODE = "user-management";

    @EntityAttributePolicy(entityClass = User.class, attributes = "*", action = EntityAttributePolicyAction.MODIFY)
    @EntityPolicy(entityClass = User.class, actions = EntityPolicyAction.ALL)
    void user();
}
1 The API scope indicates the role will be applied for REST API requests

After these properties are defined in the application it should be possible to obtain access tokens. In this example, we will use the curl command-line tool to interact with the REST API.

curl -X POST http://localhost:8080/oauth2/token \
   --basic --user my-client:my-secret \
   -H "Content-Type: application/x-www-form-urlencoded" \
   -d "grant_type=client_credentials"
В Windows удалите символы \ и вводите команду одной строкой.

Вы должны получить ответ подобный этому:

HTTP/1.1 200
{
  "access_token":"hKhgNyGMTqaKd6prH-GoHF8zFVTSr9tKKyE3OnMoafRO4FT4Xq_cewHr28cIRITaRmF0olRXpVTyFdxcOPTAl8Vc7xopHrdNuXNXwEeBn7NSiEMvQXW5zO0dwMn_H8FQ",
  "token_type":"Bearer",
  "expires_in":299
}

Атрибут access_token — это токен, который можно использовать для дальнейших запросов в заголовке Authorization. Он действует как временные учетные данные, которые предоставляют вам доступ к приложению от имени пользователя.

Запрос списка сущностей

С токеном доступа вы можете использовать операции (endpoints) REST API для загрузки списка пользователей. Замените <access_token> значением, полученным на предыдущем шаге. Мы извлечем всех пользователей в приложении через Entities API:

curl -X GET http://localhost:8080/rest/entities/User \
    -H "Authorization: Bearer <access_token>"

Ответ будет содержать всех пользователей, доступных в приложении:

HTTP/1.1 200
[
  {
    "_entityName": "User",
    "_instanceName": "[admin]",
    "id": "60885987-1b61-4247-94c7-dff348347f93",
    "version": 1,
    "active": true,
    "username": "admin"
  }
]