You can have a look at the fastapi-users module that implements a cookie-based authentication (it implements other user-management-related stuff as well, so it is worth a look anyway!).
According to the coookie docs:
Configuration
from fastapi_users.authentication import CookieAuthentication
SECRET = "SECRET"
auth_backends = []
cookie_authentication = CookieAuthentication(secret=SECRET, lifetime_seconds=3600)
auth_backends.append(cookie_authentication)
As you can see, instantiation is quite simple. You just have to define
a constant SECRET which is used to encode the token and the lifetime
of the cookie (in seconds).
You can also define the parameters for the generated cookie:
- cookie_name (fastapiusersauth): Name of the cookie.
- cookie_path (/): Cookie path.
- cookie_domain (None): Cookie domain.
- cookie_secure (True): Whether to only send the cookie to the server via SSL request.
- cookie_httponly (True): Whether to prevent access to the cookie via JavaScript.
- cookie_samesite (lax): A string that specifies the same site strategy for the cookie. Valid values are 'lax', 'strict' and 'none'.
Defaults to 'lax'.
Then you can login
with a POST
request on the /login
endpoint and set the cookie on the browser.
I found no info on the auto-OpenAPI integration, but since login is setting the cookie on the browser, you can log in once and then use the API.