Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie based Authentication in FastAPI

I am looking to integrate Cookie based authentication in my FastAPI App. I want the same to work seamlessly with swagger as well.

I want to have a route (e.g., /login) which sets my browser cookies. All other protected route uses Depends in the decorator to verify the key present in cookie. How do I get this to work with OpenAPI authorize button?

An important factor here is integration with Swagger/OpenAPI docs auto-generated by FastAPI.

like image 641
Irfanuddin Avatar asked May 28 '26 23:05

Irfanuddin


1 Answers

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 cookie 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.

like image 50
John Moutafis Avatar answered May 31 '26 19:05

John Moutafis