user728650
user728650

Reputation: 1986

jwt served via httponly cookie with someway to find out is-logged-in

While building a javascript SPA (single page application) I need to display some pages differently based on if the user is logged in or not.

Auth is handled by JWT which is served via httpOnly cookie and secure headers.

That leaves cookie not accessible from the SPA javascript and that in turn means I don't know if the user is logged in or not.

I did check some posts on how to solve this problem and found some suggestions like

I am late to the SPA party but I am sure this has to be a long solved problem. I am unable to see something obvious I guess.

Please point me to the right direction.

For completeness, here are some unanswered, semi answered related posts

Upvotes: 18

Views: 4435

Answers (2)

Yaakoub Belhardi
Yaakoub Belhardi

Reputation: 1

Actually yes i use rtk Query and send the response data to the localStorage

const initialState = {
  userInfo:
    typeof window !== "undefined" && localStorage.getItem("userInfo")
      ? JSON.parse(localStorage.getItem("userInfo") || "{}")
      : null,
} as AuthState;
// #5

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setCredentials: (state, action) => {
      state.userInfo = action.payload;
      localStorage.setItem("userInfo", JSON.stringify(action.payload));
    },
    logout: (state) => {
      state.userInfo = null;
      localStorage.removeItem("userInfo");
    },
  },
});

export const { setCredentials, logout } = authSlice.actions;
export default authSlice.reducer;

Upvotes: -1

Benoit Tremblay
Benoit Tremblay

Reputation: 728

You have basically two choices:

Save that the user is logged in with a second non-http cookie that expires

Pros

  • No addition HTTP request required
  • No latency before you know if the user is logged in

Cons

  • You need to keep the expiration and renewal of both cookies in sync
  • If your cookies are not in sync anymore because of an edge case, you will need to detect it and act accordingly

Use an HTTP request that will tell you if the user is logged in or not

Pros

  • Less error prone
  • No need to change the backend

Cons

  • You still need to detect if the user is no longer logged in while the user is using the app

Upvotes: 11

Related Questions