How to authorize OpenAPI/Swagger UI page in FastAPI?

Question:

I’m building a FastAPI application with OAuth2 and JWT authentication. I’ve got two endpoints that create the JWT token. The first is hidden from the OpenAPI page but is used by the page Authorize button. The second does the same functionality but is available to the users as an API endpoint.

If the user uses the page Authorize button and successfully gets authenticated, the rest of the API endpoints on the OpenAPI page become accessible.

If the user uses the API get_token endpoint only, they get a valid JWT token, which can be used with the protected API’s, but the OpenAPI page isn’t authenticated.

How can I use the token returned by the public get_token API endpoint to authenticate the OpenAPI page as if the user went through OpenAPI provided Authorize functionality?

Asked By: writes_on

||

Answers:

When using the Authorize button, the Authorization header with the token in it is automatically sent in every subsequent request you make to the FastAPI backend, and hence, the user gets authenticated.

Using your get_token endpoint, users will obtain the token as a response, and have to manually place it in the headers for every request they make. As described in this answer, as Authorization is a reserved header in Swagger UI/OpenAPI specification, you either have to define a Header parameter in your endpoints with a different name, e.g., token, where users will place the token value (see this answer as well), or use the Authorize button, which will automatically add it for every request to any endpoint of your server.

Another option would be to create an httponly cookie (using the Set-Cookie header) with the token inside once the user calls the get_token endpoint, and return the cookie with the Response object, as described here and here. The browser will store the cookie sent by the server and will send it back with every request made to the server inside a Cookie HTTP header (read more about cookies here). Inside the endpoint, you can then retrieve the token using the Request object directly, for example, request.cookies.get('token'), or by defining a cookie parameter for it.

Answered By: Chris