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 (Eg...
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 (eg: /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?
Important factor here is integration with Swagger/OpenAPI docs auto generated by FastAPI.
1 Answer
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.