How are cookie-http-only sessions supposed to work on a SPA with a separate API server?

一笑奈何 提交于 2020-04-17 18:46:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!