Метод POST /api/v1/auth/logout

Документация API: Деактивация сессии пользователя (Logout)

Author

Application & Simulation Services Framework Documentation

Published

July 2, 2026

WarningОграничение публичной документации

В открытом доступе представлена демонстрационная версия метода. В настоящей публичной документации отображены не все шаги, технические сценарии и приватные эндпоинты для системы цифровых симуляторов бизнес-процессов.

  • Полная спецификация метода: Будет доступна только во внутреннем контуре разработки (Confluence / Swagger Enterprise).

Функциональное назначение

This method is designed to correctly and securely terminate the current user session in the system.

Under the new distributed architecture, the POST /logout method addresses three primary tasks:

  1. Refresh Token Revocation: Sets the is_revoked flag of the target refresh_token to true in the user_sessions table.
  2. WebSocket Manager Resource Cleanup: Sends an internal asynchronous signal to the gateway’s RAM to forcefully close the currently active WSS stream (/ws/push-stream/{id}) specifically for this device.
  3. Secure UI State Reset: Triggers the mobile application to completely clear local Secure Storage and redirect the interface to the initial login screen.

Interaction Protocol (HTTP Contract)

  • Method: POST
  • Route: /api/v1/auth/logout
  • Data Format: application/json

Header Specification (HTTP Headers)

Header Required Description Example Value
Content-Type Yes Specifies JSON payload transmission application/json
Authorization Yes Access Token. The gateway extracts user_id and home_group_id from it. Bearer eyJhbGciOiJIUzI1Ni...
X-Request-ID Yes End-to-end request ID for logout session tracing req-auth-out-77aa

Request Body Specification (Request Body)

The client explicitly passes the current valid refresh_token in the request body, which is to be revoked in the database.

Field Type Required Description Example Value
refresh_token String Yes The refresh token that needs to be revoked in the DBMS ref-token-xyz789...

Request JSON Example (Payload):

{
  "refresh_token": "ref-token-xyz789_v1_signature..."
}

Метод предназначен для корректного и безопасного завершения текущей пользовательской сессии в системе .

В рамках новой распределенной архитектуры метод POST /logout решает три основные задачи:

  1. Отзыв токена обновления (Revocation): Переводит флаг is_revoked целевого refresh_token в состояние true в таблице user_sessions.
  2. Очистка ресурсов WebSocket-менеджера: Отправляет внутренний асинхронный сигнал в оперативную память шлюза, чтобы принудительно закрыть текущий активный WSS-стрим (/ws/push-stream/{id}) именно для этого девайса.
  3. Безопасный сброс состояния UI: Служит триггером для мобильного приложения для полной очистки локальных хранилищ Secure Storage и переключения интерфейса на стартовый экран авторизации.

Протокол взаимодействия (HTTP Контракт)

  • Метод: POST
  • Маршрут: /api/v1/auth/logout
  • Формат данных: application/json

Спецификация заголовков (HTTP Headers)

Заголовок Обязательный Описание Пример значения
Content-Type Да Указывает на передачу JSON-пакета application/json
Authorization Да Токен доступа (Access Token). Шлюз вычитывает user_id и home_group_id. Bearer eyJhbGciOiJIUzI1Ni...
X-Request-ID Да Сквозной ID запроса для трассировки сессии выхода из системы req-auth-out-77aa

Спецификация тела запроса (Request Body)

В теле запроса клиент явно передает текущий валидный refresh_token, который подлежит удалению в базе данных.

Поле Тип Обязательный Описание Пример значения
refresh_token String Да Токен обновления, который необходимо аннулировать в СУБД ref-token-xyz789...

Пример JSON-запроса (Payload):

{
  "refresh_token": "ref-token-xyz789_v1_signature..."
}

Диаграмма последовательности (Mermaid)

ImportantDocumentation Under Development

This documentation section is currently under development and may contain incomplete data. Some technical descriptions, parameters, and system operation scenarios for the digital business process simulator are subject to change.

  • Stable documentation version: Will be published upon final completion and validation of the method code.

The diagram illustrates the secure logout logic (POST /logout). The Auth service revokes the refresh_token, after which the gateway accesses its active connections pool and forcefully terminates the WebSocket stream for this specific smartphone.

sequenceDiagram
    autonumber
    actor App as APP (Mobile App)
    participant Nginx as Nginx Proxy
    participant GW as GATEWAY (backend-api)
    participant Auth as AUTH (auth-service)
    participant Redis as REDIS (Token Blacklist)
    participant DB as DB_AUTH (PostgreSQL)

    App->>Nginx: Step 1: POST /api/v1/auth/logout (Bearer Access / Body Refresh)
    activate Nginx
    Nginx->>GW: Step 2: POST /backend-api/v1/auth/logout
    activate GW
    GW->>Auth: Step 3: gRPC: LogoutUser(LogoutRequest)
    activate Auth
    
    Auth->>Redis: Step 4: Redis.SET(blacklist:access, ex=TTL)
    activate Redis
    note over Auth, Redis: If Redis Fails:<br/>Fail-Close -> Emergency Logout HTTP 503
    Redis-->>Auth: Token successfully blocked in cache
    deactivate Redis
    
    Auth->>DB: Step 5: SQL UPDATE user_sessions SET is_revoked = true...
    activate DB
    DB-->>Auth: Session status updated in DB
    deactivate DB
    
    Auth-->>GW: Step 6: gRPC: LogoutResponse
    deactivate Auth
    GW-->>App: Step 7: HTTP 200 OK (status: success)
    deactivate GW
    deactivate Nginx
    
    note over App: Step 8: Internal method<br/>SecureStorage.deleteAll() and redirect

Secure Logout Process

На диаграмме представлена логика безопасного выхода из системы (POST /logout). Сервис Auth отзывает refresh_token, после чего шлюз обращается к своему пулу активных соединений и принудительно “тушит” WebSocket-стрим этого смартфона.

sequenceDiagram
    autonumber
    actor App as APP (Мобильное приложение)
    participant Nginx as Nginx Proxy
    participant GW as GATEWAY (backend-api)
    participant Auth as AUTH (auth-service)
    participant Redis as REDIS (Token Blacklist)
    participant DB as DB_AUTH (PostgreSQL)

    App->>Nginx: Шаг 1: POST /api/v1/auth/logout (Bearer Access / Body Refresh)
    activate Nginx
    Nginx->>GW: Шаг 2: POST /backend-api/v1/auth/logout
    activate GW
    GW->>Auth: Шаг 3: gRPC: LogoutUser(LogoutRequest)
    activate Auth
    
    Auth->>Redis: Шаг 4: Redis.SET(blacklist:access, ex=TTL)
    activate Redis
    note over Auth, Redis: If Redis Fails:<br/>Fail-Close -> Emergency Logout HTTP 503
    Redis-->>Auth: Токен успешно заблокирован в кэше
    deactivate Redis
    
    Auth->>DB: Шаг 5: SQL UPDATE user_sessions SET is_revoked = true...
    activate DB
    DB-->>Auth: Статус сессии обновлен в БД
    deactivate DB
    
    Auth-->>GW: Шаг 6: gRPC: LogoutResponse
    deactivate Auth
    GW-->>App: Шаг 7: HTTP 200 OK (status: success)
    deactivate GW
    deactivate Nginx
    
    note over App: Step 8: Internal method<br/>SecureStorage.deleteAll() and redirect

Процесс безопасного выхода (Logout)

Расшифровка шагов

ImportantDocumentation Under Development

This documentation section is currently under development and may contain incomplete data. Some technical descriptions, parameters, and system operation scenarios for the digital business process simulator are subject to change.

  • Stable documentation version: Will be published upon final completion and validation of the method code.
Step Action Parameters / Requests / DTO Errors (Exceptions / Statuses)
1 (App -> Nginx) The user taps “Log Out”. The client sends a request passing the Access Token in the header and the current Refresh Token in the body for revocation. HTTP POST /api/v1/auth/logout
Headers: Authorization: Bearer <Access_JWT>
Payload (LogoutRequestDTO):
{ "refresh_token": "ref-token-xyz789_v1_signature..." }
HTTP 401 Unauthorized (access token is modified, forged, expired, or missing)
2 (Nginx -> Gateway) The proxy server forwards the session revocation command to the internal API gateway while preserving headers. HTTP POST /backend-api/v1/auth/logout
Headers:
X-Request-ID: "req-auth-out-77aa", Authorization
No business errors
3 (Gateway -> Auth) The API gateway extracts user_id and metadata from the token and sends a gRPC request to forcefully terminate the session. Protocol: gRPC
Method: LogoutUser(LogoutRequest)
Parameters: refresh_token, user_id
gRPC Status: INVALID_ARGUMENT (invalid or empty identifiers/tokens provided)
4 (Auth -> Redis) Blacklist Invalidation: The remaining time-to-live (Remaining TTL) of the Access Token is calculated in the service memory, and the token is added to the Redis Blacklist. Redis Command (Access JWT Block):
SET "blacklist:access:eyJhbGci..." "revoked" EX 450
(Where 450 seconds is the dynamic token TTL remainder)
Fail-Close Emergency Exit:
Returns a business status HTTP 503 Service Unavailable to the client when session security cannot be guaranteed
5 (Redis -> Auth) Redis confirms successful recording and blocking of the access token in the cache RAM. Cache response: Status OK. No business errors
6 (Auth -> DB_Auth) The service terminates the session in PostgreSQL, switching the token status to revoked by its hash. SQL Query:
UPDATE user_sessions SET is_revoked = true WHERE refresh_token_hash = 'hash_of_token...' AND user_id = 'user-uuid';
No business errors
7 (DB_Auth -> Auth) The database updates the row status and confirms the session closure. DBMS response: Status UPDATE 1 (1 row successfully modified). Session not found (if no record with such token hash or user_id exists in the DB, the DBMS will return UPDATE 0)
8 (Auth -> Gateway) The authorization service returns a successful gRPC response, confirming the blockade of all session tokens. Protocol: gRPC
Response: LogoutResponse
Payload: success: true
No business errors
9 (Gateway -> App) The gateway returns a successful HTTP status via Nginx, confirming session closure in the system. HTTP Status at Nginx exit: 200 OK
Response Body:
json<br/>{<br/> "status": "success",<br/> "data": {<br/> "message": "SESSION_TERMINATED",<br/> "details": "Refresh token successfully revoked. Active WebSocket connection terminated clean.",<br/> "timestamp": "2026-07-02T02:20:00Z"<br/> }<br/>}<br/>
No business errors
9 Continued (App -> App) UI State Reset: The mobile application completely purges local storage and switches the interface to the login screen. Internal application method:
SecureStorage.deleteAll() and instant redirection of the user to the initial login screen.
No business errors
Шаг Действие Параметры / Запросы / DTO Ошибки (Исключения / Статусы)
1 (App -> Nginx) Пользователь нажимает «Выйти». Клиент отправляет запрос, передавая Access Token в заголовке и текущий Refresh Token в теле для аннулирования. HTTP POST /api/v1/auth/logout
Headers: Authorization: Bearer <Access_JWT>
Payload (LogoutRequestDTO):
{ "refresh_token": "ref-token-xyz789_v1_signature..." }
HTTP 401 Unauthorized (токен доступа изменен, подделан, просрочен или отсутствует)
2 (Nginx -> Gateway) Прокси-сервер транслирует команду на отзыв сессии на внутренний API-шлюз с сохранением заголовков. HTTP POST /backend-api/v1/auth/logout
Headers:
X-Request-ID: "req-auth-out-77aa", Authorization
Бизнес-ошибки отсутствуют
3 (Gateway -> Auth) API-шлюз извлекает user_id и метаданные из токена и направляет gRPC-запрос на принудительное закрытие сессии. Протокол: gRPC
Метод: LogoutUser(LogoutRequest)
Параметры: refresh_token, user_id
gRPC Status: INVALID_ARGUMENT (переданы некорректные или пустые идентификаторы/токены)
4 (Auth -> Redis) Инвалидация через Блэклист: Оставшееся время жизни (Remaining TTL) Access-токена вычисляется в памяти сервиса, и токен вносится в Redis Blacklist. Redis Команда (Блокировка Access JWT):
SET "blacklist:access:eyJhbGci..." "revoked" EX 450
(Где 450 секунд — динамический остаток TTL токена)
Fail-Close Аварийный выход:
Возврат бизнес-статуса HTTP 503 Service Unavailable для клиента при невозможности гарантировать безопасность сессии
5 (Redis -> Auth) Redis подтверждает успешную фиксацию и блокировку токена доступа в оперативной памяти кэша. Ответ кэша: Статус OK. Бизнес-ошибки отсутствуют
6 (Auth -> DB_Auth) Сервис выполняет закрытие сессии в PostgreSQL, переводя токен в состояние отозванного по его хэшу. SQL-запрос:
UPDATE user_sessions SET is_revoked = true WHERE refresh_token_hash = 'hash_of_token...' AND user_id = 'user-uuid';
Бизнес-ошибки отсутствуют
7 (DB_Auth -> Auth) База данных выполняет изменение статуса строки и подтверждает закрытие сессии. Ответ СУБД: Статус UPDATE 1 (успешно изменена 1 строка). Сессия не найдена (если запись с таким хэшем токена или user_id отсутствует в БД, СУБД вернет UPDATE 0)
8 (Auth -> Gateway) Сервис авторизации возвращает успешный gRPC-ответ, подтверждая блокировку всех токенов сессии. Протокол: gRPC
Ответ: LogoutResponse
Payload: success: true
Бизнес-ошибки отсутствуют
9 (Gateway -> App) Шлюз возвращает успешный HTTP-статус через Nginx, подтверждая закрытие сессии в системе. HTTP Статус на выходе Nginx: 200 OK
Response Body:
json<br/>{<br/> "status": "success",<br/> "data": {<br/> "message": "SESSION_TERMINATED",<br/> "details": "Refresh token successfully revoked. Active WebSocket connection terminated clean.",<br/> "timestamp": "2026-07-02T02:20:00Z"<br/> }<br/>}<br/>
Бизнес-ошибки отсутствуют
9 Продолжение (App -> App) Сброс стейта UI: Мобильное приложение полностью очищает локальное хранилище и переключает интерфейс на экран авторизации. Внутренний метод приложения:
SecureStorage.deleteAll() и мгновенный редирект пользователя на стартовый экран логина.
Бизнес-ошибки отсутствуют

Спецификация ответов сервера (Response Body)

ImportantDocumentation Under Development

This documentation section is currently under development and may contain incomplete data. Some technical descriptions, parameters, and system operation scenarios for the digital business process simulator are subject to change.

  • Stable documentation version: Will be published upon final completion and validation of the method code.

Success Response

HTTP 200 OK (Response at Step 8)

Returned to the mobile application after the successful commit of the deactivation transaction. The response body confirms successful session termination.

  • Response Headers:
    • Content-Type: application/json
  • Response Body:
{
  "status": "success",
  "data": {
    "message": "SESSION_TERMINATED",
    "details": "Refresh token successfully revoked. Active WebSocket connection terminated clean.",
    "timestamp": "2026-07-02T02:20:00Z"
  }
}

Успешный ответ (Success Response)

HTTP 200 OK (Ответ на Шаге 8)

Возвращается мобильному приложению после успешного коммита транзакции деактивации. В теле ответа фиксируется успешное удаление сессии.

  • Заголовки ответа (Response Headers):
    • Content-Type: application/json
  • Тело ответа (Response Body):
{
  "status": "success",
  "data": {
    "message": "SESSION_TERMINATED",
    "details": "Refresh token successfully revoked. Active WebSocket connection terminated clean.",
    "timestamp": "2026-07-02T02:20:00Z"
  }
}

Protobuf Контракт

Данный gRPC-контракт для взаимодействия между API-Шлюзом и Сервисом Авторизации.

syntax = "proto3";

package auth.v1;

option go_package = "auth/v1;authv1";
option java_multiple_files = true;
option java_package = "com.auth.v1";

// Сервис управления сессиями и авторизацией
service AuthService {
  // Принудительное аннулирование сессии пользователя (Safe Logout)
  rpc LogoutUser (LogoutRequest) returns (LogoutResponse);
}

// Запрос на отзыв сессии (Шаг 3 диаграммы)
message LogoutRequest {
  // Токен обновления, подлежащий деактивации в БД
  string refresh_token = 1;
  
  // Уникальный идентификатор пользователя, извлеченный шлюзом из Access-токена
  string user_id = 2;
}

// Ответ на запрос отзыва сессии (Шаг 6 диаграммы)
message LogoutResponse {
  // Флаг успешности проведения операции в Redis и СУБД
  bool success = 1;
  
  // Текстовый статус для логирования на стороне шлюза (опционально)
  string message = 2;
}