问题
When trying to figure out how to authenticate with Facebook/Google in the context of an SPA I'm building, someone pointed me to Stop using JWT for sessions.
I'm trying to give it a try, using HTTP-Only Cookies. My server is Ruby on Rails with Devise and my client is JavaScript with React, although the conceptual solution is independent of specific tech I believe.
My app gets loaded by going to projectx.lvh.me
and then it makes a query to api.projectx.lvh.me
to fetch the current user. At the beginning it's null because the user is not logged in. When a call request is made to sign in, the response from api.projectx.lvh.me
contains the session cookie, hurra! But the next request that projectx.lvh.me
makes to api.projectx.lvh.me
doesn't carry the cookie, so, it seems the cookie is forever lost. Even opening api.projectx.lvh.me
on another tab doesn't show the cookie. Is this supposed to work? What am I missing?
I thought this was blocked by third-party cookie blocking and that's why we can't use cookies in this scenario and we have to use jwt tokens (stored on a cookie, local storage or session storage).
回答1:
I managed to get cookies working in this scenario by adding config/initializers/session_store.rb
to my Rails app containing:
Rails.application.config.session_store :cookie_store, key: 'session', domain: :all
which caused the session cookie to not be for api.projectx.lvh.me
but for .projectx.lvh.me
.
On the frontend, the API calls needed to include withCredentials
, which with Axios it was the withCredentials
option set to true:
Axios.post(`${apiEndPoint()}/users`, { user: values }, { withCredentials: true })
and with fetch
it was the credentials
option set to "include"
:
fetch(`${apiEndPoint()}/graphql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: "include",
body: JSON.stringify({
query: operation.text,
variables,
}),
})
来源:https://stackoverflow.com/questions/60579293/how-are-cookie-http-only-sessions-supposed-to-work-on-a-spa-with-a-separate-api