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: /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.

4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest