I’m writing an OpenAPI spec for an external API. The API requires two steps for authentication. The user first needs to GET /
to obtain a session cookie and a CSRF token. Then, the user logs into via POST /login
with the session cookie and logs into the session.
Is there something more elegant that I can do with OpenAPI than the following?
components:
securitySchemes:
sessionCookie:
type: apiKey
in: cookie
name: session
parameters:
CSRFTokenHeader:
name: X-CSRF-TOKEN
in: header
required: false
schema:
type: string
schemas:
LoginRequest:
type: object
required:
- username
- password
- _csrf
properties:
username:
type: string
password:
type: string
_csrf:
type: string
description: CSRF token obtained from initial request
paths:
/:
get:
tags:
- session
operationId: getInitialSession
/login:
post:
tags:
- session
operationId: loginUser
security:
- sessionCookie: []
requestBody:
required: true
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/LoginRequest'
I’m using @openapitools/openapi-generator-cli
to generate a Python client and the resulting code looks as follows.
session_api = my_api.SessionApi(api_client=client)
init_result = session_api.get_initial_session_with_http_info()
assert init_result.headers
client.cookie = init_result.headers["Set-Cookie"]
csrf_token = init_result.headers["X-CSRF-TOKEN"]
session_api.login_user_with_http_info(
username=os.environ.get("MY_API_USERNAME"),
password=os.environ["MY_API_PASSWORD"],
csrf=csrf_token,
)