nhost-js-sdk
nhost-js-sdk copied to clipboard
HttpOnly Cookies auth flow is flawed.
I spend some time trying to get this right. Here are my findings:
- You need to set
useCookies
setup parameter to true, by default is false. -
Auth.refreshSession
public method does not work because it does not allow you to pass a refresh token, which can be null but needs to be present forAuth._refreshToken
to trigger a refresh token request. -
Auth.getJWTToken
does not work because there is no previous session, the cookie is not accessible by javascript code but it will be available to the request. - The only remaining way to refresh the token is private method
Auth._autoLogin
since it is private you need to call it by not disabling setup parameterautoLogin
, which is true by default, but the funny part is that, as stated in 2, you NEED to pass a non-falsy value as refreshToken forAuth._refreshToken
to work, so you need to load the page with a dummy query string, assuming you are running on port 3000 that would belocalhost:3000?refresh_token=dummy string that won't be used
. - To know is the user is logged in you need to register a listener for
Auth.onAuthStateChanged
but after that you need to callAuth.user
to get the user info into the your app state.
So, it is possible to get it working, it is not documented at all, please correct me if I am wrong, but with a few caveats, like the query string. I don't think it is a bug, and I prefer not to suggest changes to make it work before knowing your thoughts about it. But this is a feature I think it is particularly useful considering that HttpOnly cookies are mentioned as recommended ways to store JWT refresh tokens.
How about using NextAuth
for the authentication flows? After v4 they have a very modular flow and you could implement their flows into Nhost with their adapters. Might be worth a thought.