Cookie based Authentication in FastAPI - openapi

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.

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.

Related

Persisting user state in sveltekit

I'm trying to hook up a Strapi backend to a SvelteKit frontend, and stuck on how to persist user login state so that everything doesn't just reset on refresh, or when navigating to a new page. I've tried:
Storing the jwt and user object issued by Strapi in localStorage and initializing the Svelte store with it. Seemed like I was getting close, but a) I couldn't do export const user = writable(localStorage.user) because that code was running in the browser, and I couldn't wrap it in an if (browser) {...} because import and export can only appear at the top level. Also tried a function in hooks.js to read the contents of localStorage and update the store, but it seems that functions getting called from there run on the server, even if it's the same function that works to access localStorage on login... and plus b) from what I gather, storing jwt's in localStorage is insecure.
Storing the jwt and user object in an http only cookie. Cookies and http headers seem really confusing, and I had a hard time manipulating them to store the jwt and put it in each header. But I think what really stumped me was essentially the same SSR issue of never knowing essentially how to successfully interface between the client and server. I.e. if (browser) {...} never seemed to work, or I couldn't get it to, anyway. (Happy to provide more code details on what I tried here if needed. It's a mess, but it's saved in git.)
I know this is a thing every app that has users needs to do, so I'm sure there's a way to do it in SvelteKit. But I can't find anything online that explains it, and I can't figure it out from the official docs either.
So am I missing something easy? (Probably.) Or is there a tricky way to do this?
For a SvelteKit SPA authenticating to Strapi, here's the happy path flow I would use:
SvelteKit page /routes/login.svelte collects the username (identifier) and password and a button's on:click handler posts those values via fetch to your own /routes/auth.js:post() endpoint. Why? Because now your server's endpoint is handling the login on behalf of the user so you can set an httpOnly cookie in the response.
In your auth.js endpoint post() method, you will want to do a few things:
Use fetch to post identifier and password to Strapi authentication (http://localhost:1337/auth/local) to get the JWT (response.body.jwt)
Use fetch to get user info from Strapi (http://localhost:1337/users/me). In the get, add a header called 'Authentication' with a value of 'Bearer ' + the JWT you just received from Strapi in the previous step
Return the user info from the response from Strapi and pass it back to your client in the response.body
Set a header httpOnly cookie with the value of the JWT.
Back on the client in the last part of the login button's on:click handler, take the user info from res.json() and put it in a writeable store called user or in the SvelteKit session store...
import { session } from '$app/stores'
...
const loginClickHandler = async () => {
...
const fromEndpoint = await res.json()
session.set({ user: fromEndpoint.user })
}
At this point, you have the user information persisted client-side and the JWT as an httpOnly cookie that can't be read or modified by client-side JavaScript code. Each request you make to your own server's pages or endpoints will send the JWT cookie along.
If you want to logout, call an endpoint on your server (/auth/logout) that sets the existing jwt cookie to have an Expires based on the current date/time:
response.headers['Set-Cookie'] = `jwt=; Path=/; HttpOnly; Expires=${new Date().toUTCString()}`
You would also want to clear the user object in your store (or the session store).
The main takeaway for the above example is that your client would never directly talk to Strapi. Strapi's API would be called only by your SvelteKit server's endpoints. The httpOnly jwt cookie representing your session with Strapi would be included in every request to your server's endpoints to use/validate with Strapi's API (or delete if expired or the user logged out).
There are lots of other approaches but I prefer this one for security reasons.

storing and sending jwt httponly cookie, and csrf token with postman

I have a flask API, with jwt authentication, on a httponly cookie. I installed interceptor, added the domain(with HTTPS) to the list, and enabled the requests and cookies interception.
but still,
how do I make postman send the cookie I got from logging in to the server? usually, with a simple front-end, it just happens, so I didn't think about it.
all the methods I found in postman documentation, including specifying the value with the token, but I don't have it, since I can't access the httponly cookie. (or can I?)
must I access the cookies? can it be done automatically like simply sending requests from the front-end?
any guidance will be appreciated
After a full evening of research, I did two things to make it work -
in the login request, I added a "test" script(a post-request script in postman), with the following code:
const csrf_token = pm.response.headers.get("set-cookie");
const edited_token = csrf_token.split(/[;=]/)[1];
pm.environment.set("X-CSRF-TOKEN", edited_token);
console.log(csrf_token.split(/[;=]/)[1]);
First, I got the cookie from the response, and then used a regex to separate only the token value, and set it as an environment variable. this way, I could add it as a header later, for accessing protected URLs.
The second step was to add a pre-scrit in any request with a protected URL -
in the pre-request tab, I added the following:
pm.request.headers.add({
key: 'X-CSRF-TOKEN',
value: pm.environment.get("X-CSRF-TOKEN")
});
Which only added the same token I took earlier from the "X-CSRF-TOKEN" environment variable and set it to the header.
Mission accomplished :)
I hope it will help others who bumped into this

How to access protected assets in Play Silhouette with JWT Authenticator

I have Play with Silhouette authentication and authorization configured using the JWTAuthenticator. This authenticator works by reading the X-Auth-Token header, which is a jwt, to identify user in every request. This works fine for REST endpoints.
Now I have images that only owners should be able to access it, and I would like to use those in background-image css property (this is a requirement). In such scenario I'm not able to set the request header hence the request will be denied.
The next natural step is to embed the token in the background-image url itself as an url parameter. However I don't know then how to proceed at the server side. How can I tell the JWTAuthenticator to use the token in the url if not X-Auth-Token header is present?
Ok, I'm sharing here my founds so hopefully this can help others. While digging into silhouette code I found that we can easily configure from which part(s) of the request (header, query string, ...) we want to read the token. By default the jwt token is read from the X-Auth-Token header, but we can configure the JWTAuthenticator to read the token also from a query string variable:
val config =
configuration.underlying
.as[JWTAuthenticatorSettings]("silhouette.authenticator")
// this is the important line of code
.copy(requestParts = Some(Seq(RequestPart.Headers, RequestPart.QueryString)))
new JWTAuthenticatorService(config, None, encoder, idGenerator, clock)
Now if you want to use a protected asset behind a controller with a silhouette.SecureAction then you just need to add the X-Auth-Token as query string parameter to the url:
.my-class {
background-image: url("/image?X-Auth-Token=........")
}

can I pass headers to redirected location after redirection?

here's response header of my redirection endpoint with status code 302.
"Location": "http://<target-domain>",
"Set-Cookie": "username=user1;"
I can see it redirects correctly to 302. but the cookie does not get set on the <target-domain>
Looks like the header "Set-Cookie": "username=user1;" does not get passed to the <target-domain> on redirection.
I see 2 network activities in my development tool,
redirection endpoint responds with status code 302. I see Location and Set-Cookie in the response header.
target domain responds with status code 200. I don't see Location and Set-Cookie anymore.
Is there a way to set the cookies on the <target-domain>?
You can't set cookies on a domain other than the one you're on, so basically no. The only exception to this is you can set cookies on example.com if your current domain is something like subdomain.example.com, where you can attach the cookies to a shorter form of your domain, but it must be the same base domain.
If you need the other site to set a cookie with a value it does not know, you'll have to pass that value through somehow. Using a redirect with a query string leaves it open to tampering by the user unless you cryptographically sign it (annoying) or ship over a token that can be used to retrieve the raw value. You may need a short-term store for this, like Redis, Memcached, or even a database row you can purge later.
If it were possible to set cookies on any domain at all there'd be utter chaos. These things are heavily restricted for a reason.

Is Play2.5 session cookie encrypted?

I'm starting to learn Play framework with Scala and I'm trying to set the session cookie.
I have the play.crypto.secret config set and also the settings for the cookie like this
play.http {
session {
httpOnly = true
domain = "localhost"
}
}
Is it normal that I see the content of the cookie in the console without problems?
for example:
As mentioned in official Play documentation, play.crypto.secret is used for signing session cookies and CSRF tokens. That's means that you will see cookie values on a client side, but they will be encrypted with the secret key.
No, the cookie is not encrypted. It is signed, meaning that part of the cookie (or a separate cookie) contains a signature value calculated using the cookie value itself and the secret key.