Alternative to saving JWT token in local storage?

What is the secure standard for saving authorization/authentication with GraphQL/Apollo Client and Server.

Currently in both the course I am taking and the Apollo docs, they are of saving a JWT token into local storage and attaching it to any header requests to the server to be validated on the server-side.

I understand that saving a token into localstorage is a severe vunerablity.

So what are the safest alternatives? Is there a way to save a JWT token into a cookie? Is saving the token into a cookie the "industry" standard?

Even in the Apollo docs they use localstorage
https://www.apollographql.com/docs/react/networking/authentication/

import { setContext } from '@apollo/client/link/context';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});```

>Solution :

you can use sessionStorage, it remove the data when session finish and the values can access only by your web, more info here: https://developer.mozilla.org/es/docs/Web/API/Window/sessionStorage

or To keep them secure, you should always store JWTs inside an httpOnly cookie. from: https://blog.logrocket.com/jwt-authentication-best-practices/

Leave a Reply