nhost-js-sdk icon indicating copy to clipboard operation
nhost-js-sdk copied to clipboard

HttpOnly Cookies auth flow is flawed.

Open migsar opened this issue 3 years ago • 1 comments

I spend some time trying to get this right. Here are my findings:

  1. You need to set useCookies setup parameter to true, by default is false.
  2. 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 for Auth._refreshToken to trigger a refresh token request.
  3. 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.
  4. 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 parameter autoLogin, 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 for Auth._refreshToken to work, so you need to load the page with a dummy query string, assuming you are running on port 3000 that would be localhost:3000?refresh_token=dummy string that won't be used.
  5. To know is the user is logged in you need to register a listener for Auth.onAuthStateChanged but after that you need to call Auth.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.

migsar avatar Jul 10 '21 17:07 migsar

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.

dohomi avatar Jan 27 '22 01:01 dohomi