Skip to content
Educora
University25 min13 / 14

Access rights, RLS and integration: JSON, XML, HTTP services

Decide who can see and change what with roles and rights, set up record-level security (RLS), exchange data as JSON and XML, write an HTTP service and call external APIs.

Check yourself
In this lesson you will learn
  • Design roles with basic and interactive rights and check rights in code
  • Build an RLS restriction with session parameters and explain its effects
  • Work with JSON/XML, create an HTTP service and call an external HTTP API

In a real project, writing code is only half the job. Murad, a storekeeper, must see only the documents of his own warehouse and must not see salaries at all. An online shop's website must get stock levels from 1C every minute, and 1C must load exchange rates from a bank. This lesson covers two professional skills of a 1C developer: security and integration.

Roles and access rights

A role (Общие › Роли) is a set of rights for each metadata object. A user can have several roles, and rights add up: if at least one role grants a right, the user has it. There is no “denying” role — so make roles small and purposeful: Кладовщик (storekeeper), Бухгалтер (accountant), ЧтениеСправочников (read catalogs).

RightMeaning
Чтение, Добавление, Изменение, Удалениеbasic rights: any work with data, including from code
Просмотр, Редактирование, Интерактивное добавление, Интерактивное удалениеinteractive rights: what a user can do in forms
Проведение, Отмена проведенияposting and unposting documents
Администрирование, Монопольный режимservice rights at configuration level
1C
Если Не ПравоДоступа("Изменение", Метаданные.Документы.РасходТовара) Тогда
    ВызватьИсключение "Недостаточно прав для изменения документа";
КонецЕсли;

Если РольДоступна("Бухгалтер") Тогда
    // показываем дополнительные колонки
КонецЕсли;
ПравоДоступа() (AccessRight) checks a specific right, РольДоступна() (IsInRole) checks a role. Checking the right is more reliable: roles may later be renamed or split.

Record-level security (RLS)

A role says “you may read РасходТовара documents” but not “which ones”. For that there is RLS (record-level security): a query-like condition is attached to the Чтение, Добавление, Изменение and Удаление rights. The condition usually uses session parameters, which are filled when the session starts in the УстановкаПараметровСеанса (SessionParametersSetting) handler.

1C
// Модуль сеанса
Процедура УстановкаПараметровСеанса(ТребуемыеПараметры)
    // НастройкиПользователей - наш общий модуль
    ПараметрыСеанса.ТекущийСклад = НастройкиПользователей.СкладТекущегоПользователя();
КонецПроцедуры
1C Query
ГДЕ Склад = &ТекущийСклад
The restriction text on the Чтение right of РасходТовара in the Кладовщик role: the user sees only their own warehouse's documents. Restrictions from several roles are combined with ИЛИ (OR).

RLS has two important consequences. First, a query on a table with a read restriction raises an error if it meets a record the user may not see; to silently get only allowed records, write ВЫБРАТЬ РАЗРЕШЕННЫЕ (SELECT ALLOWED). Second, the platform adds the condition to every query, so complex RLS can slow the base down. When server code must deliberately bypass rights, use УстановитьПривилегированныйРежим(Истина) (SetPrivilegedMode) or a common module with the Привилегированный flag.

Example 1: Murad's warehouse

Storekeeper Murad must see, create and post only the receipt and sale documents of the “Ganja” warehouse, and may only read the products catalog. Design the access setup.

Show solution
1) Role Кладовщик: for ПриходТовара and РасходТовара — Чтение, Добавление, Изменение, Просмотр, Редактирование, Проведение; for Товары only Чтение and Просмотр.
2) Session parameter ТекущийСклад (type СправочникСсылка.Склады), filled in УстановкаПараметровСеанса from the user's settings.
3) RLS on the documents' Чтение and Изменение rights: ГДЕ Склад = &ТекущийСклад.
4) ВЫБРАТЬ РАЗРЕШЕННЫЕ in report and list queries.
5) Test: log in as Murad and make sure a “Baku” warehouse document is neither visible nor creatable.

Data formats: JSON and XML

1C
Данные = Новый Структура;
Данные.Вставить("code", "0001");
Данные.Вставить("name", "Çay 100 q");
Данные.Вставить("price", 4);

Запись = Новый ЗаписьJSON;
Запись.УстановитьСтроку();
ЗаписатьJSON(Запись, Данные);
ТекстJSON = Запись.Закрыть();

Чтение = Новый ЧтениеJSON;
Чтение.УстановитьСтроку(ТекстJSON);
Прочитано = ПрочитатьJSON(Чтение);   // Структура
Чтение.Закрыть();
Сообщить(Прочитано.name);
Expected output
Çay 100 q
ЗаписатьJSON (WriteJSON) turns structures, arrays and primitive values into text, and ПрочитатьJSON (ReadJSON) turns it back.

For XML there are the ЗаписьXML (XMLWriter) and ЧтениеXML (XMLReader) objects, and for structured exchange the XDTO mechanism: СериализаторXDTO writes a whole catalog item or document to XML. For exchange between distributed bases, exchange plans (Планы обмена) track changes themselves, and typical configurations exchange data with each other in the EnterpriseData format.

HTTP services, web services and external APIs

An HTTP service (Общие › HTTP-сервисы) turns 1C into a REST API. It has a root URL (for example shop), URL templates (for example /items/{code}) and methods for each template (GET, POST…). After the infobase is published on a web server, the service answers at an address like https://server/base/hs/shop/items/0001. Each method's handler is a function that takes an HTTPСервисЗапрос (request) and returns an HTTPСервисОтвет (response).

1C
// HTTP-сервис Shop, шаблон URL /items/{code}, метод GET
Функция ItemsGET(Запрос)
    Код = Запрос.ПараметрыURL["code"];
    Товар = Справочники.Товары.НайтиПоКоду(Код);
    Если Товар.Пустая() Тогда
        Возврат Новый HTTPСервисОтвет(404);
    КонецЕсли;

    Данные = Новый Структура("code, name, price", Код, Товар.Наименование, Товар.Цена);
    Запись = Новый ЗаписьJSON;
    Запись.УстановитьСтроку();
    ЗаписатьJSON(Запись, Данные);

    Ответ = Новый HTTPСервисОтвет(200);
    Ответ.Заголовки.Вставить("Content-Type", "application/json; charset=utf-8");
    Ответ.УстановитьТелоИзСтроки(Запись.Закрыть());
    Возврат Ответ;
КонецФункции
1C
// Вызов внешнего API из 1С
Соединение = Новый HTTPСоединение("api.example.com", 443, , , , 30, Новый ЗащищенноеСоединениеOpenSSL);
ЗапросHTTP = Новый HTTPЗапрос("/v1/rates?base=AZN");
Ответ = Соединение.Получить(ЗапросHTTP);
Если Ответ.КодСостояния <> 200 Тогда
    ВызватьИсключение СтрШаблон("Сервис курсов вернул код %1", Ответ.КодСостояния);
КонецЕсли;

Чтение = Новый ЧтениеJSON;
Чтение.УстановитьСтроку(Ответ.ПолучитьТелоКакСтроку());
Курсы = ПрочитатьJSON(Чтение, Истина);   // Соответствие
Чтение.Закрыть();
HTTPСоединение (HTTPConnection) parameters: server, port, user, password, proxy, timeout (seconds) and secure connection (HTTPS).
MethodWhen to choose it
HTTP service (REST, JSON)websites, mobile apps, modern systems
Web service (SOAP, WSDL)corporate and government systems that require SOAP; WS-ссылки (WS references) to consume them
Standard OData interfaceREST access to objects without writing code (/odata/standard.odata/)
Exchange plans + XMLbranches, synchronisation between 1C bases
Example 2: an API for an online shop

The website must get a product's name and price by its code. Design the service, its responses and its security.

Show solution
1) HTTP service Shop, root URL shop, template /items/{code}, method GET, handler ItemsGET.
2) Responses: product found — 200 and JSON {"code", "name", "price"}; not found — 404; empty code — 400.
3) Security: a separate user for the website with an APIShop role that has only Чтение on Товары; HTTPS only.
4) Publishing: Администрирование › Публикация на веб-сервере (Publish to web server), tick HTTP services.
5) Test: open https://server/base/hs/shop/items/0001 in a browser or with curl.

Key points

  • Roles add rights up; there is no denying role — keep roles small and purposeful.
  • RLS conditions are attached to Чтение/Добавление/Изменение/Удаление and use session parameters.
  • On tables with RLS, ВЫБРАТЬ РАЗРЕШЕННЫЕ returns only allowed records instead of an error.
  • JSON: ЗаписатьJSON/ПрочитатьJSON; for unusual keys use ПрочитатьJSON(Чтение, Истина).
  • An HTTP service provides a REST API at /hs/<root URL>/; external APIs are called with HTTPСоединение, a timeout and HTTPS.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
A user has two roles: one grants Изменение, the other does not. What is the result?