score:8
Accepted answer
you don't need to store another cookie. i suppose you use token based authentication on your endpoint, eg. jwt. then you think about this scenario:
- user send username/password to server.
- check user credentials and if there are valid, create http-only cookie with the token
const user = await getuser({ where: { email } });
const valid = await bcrypt.compare(password, user.password);
if (!valid) {
throw new userinputerror('form arguments invalid', {
invalidargs: {
'password': 'invalid password!',
},
});
}
const token = jwt.sign({ userid: user.id }, process.env.app_secret);
/
res.cookie('token', token, {
httponly: true,
maxage: 1000 * 60 * 60 * 24 * 365,
});
- write auth middlerware to put the userid onto the req for future requests to access
const jwt = require('jsonwebtoken');
const { authenticationerror } = require('apollo-server');
module.exports = async function(req, res, next) {
const { token } = req.cookies;
if (token) {
try {
const { userid } = jwt.verify(token, process.env.app_secret);
if (!userid) return next();
req.userid = userid;
} catch (e) {
console.log(e);
}
}
next();
};
- check on each request the userid. if there is no userid, user doesn't logged in
if (!req.userid) {
throw new authenticationerror('log in!');
}
- if user's token is invalid/expired you will get authenticationerror. catch it and redirect to login page.
- if your ui depends on user status, you can create easy-to-use component (i am using react) to check it.
user component:
import { query } from 'react-apollo';
import gql from 'graphql-tag';
import proptypes from 'prop-types';
const current_user_query = gql`
query current_user_query {
me {
userid
firstname
lastname
profilepictureurl
}
}
`;
const user = props => (
<query {...props} query={current_user_query} fetchpolicy={'cache-first'}>
{payload => props.children(payload)}
</query>
);
user.proptypes = {
children: proptypes.func.isrequired,
};
export default user;
if we get me
object from server, you know, there is a logged in user, so you can render depends on user's status:
import { link } from 'react-router-dom';
import react from 'react';
<user>
{({ loading, error, data: { me } }) => {
if (loading || error || !me) return (
<button component={link} to={'/login'}>login</button>
);
if(me) return (
<button component={link} to={'/dashboard'}>go to dashboard</button>
)
}}
</user>
Source: stackoverflow.com
Related Query
- Nextjs - Auth token stored in memory + refresh token in HTTP Only cookie
- http-only cookie + token : double job?
- How can we store JWT token in Http only cookies?
- How to set the Google Analytics cookie only after another consent cookie is set and "true"?
- How to set Auth token cookie from GraphQL Mutation with Apollo
- How to do render only after http request completed in ReactJS
- How to tell if a user is logged in with http only cookies and JWT in react (client-side)
- ReactJS Unexpected Token ) on Safari only
- React App + Spring Boot - JWT auth token inside a cookie is not set in Chrome
- How to implement remember me functionality for authentication in ReactJS when i only receive jwt token from backend api
- React infinite scroll- double scrollbars showing- I only want the window scroll bar
- Authenticity token only gets set after form submission in React component which throws an error in Rails
- React Router and redux auth token double render
- How to set cookie with JWT token in ReactJS frontend using Node, Express, Axios
- How to store JWT token in cookie React fetch
- Is storing access token in cookie to allow for SSR dangerous?
- http response not setting cookie in the browser
- Next JS:How to get the token stored in the cookie for a server side API call in Next JS
- Reactjs Unexpected token Error Only On Windows, Not Linux
- React StrictMode double initializasion - where to put logic that should be executed only once
- store token in cookie or local storage in reactjs
- ReactJS- Pass the JWT token as Authorization in axios method for http request
- Double filter only filters when one is active
- Google OIDC error. "Error 400: invalid_scope. Requests for only id token must contain a subset of [openid, email, profile] scopes."
- How to remove only those commas which are present inside double quotes in a string?
- How to allow only double numbers in input React js
- Redux: Make http call ONLY IF data not available in store?
- clear token cookie using react js after logout
- React — How to make a button (that prevents double clicking while handling HTTP requests)
- My cron job is always containing the same token values
More Query from same tag
- Does material-ui useStyles really requires the entire props object?
- Rendering from a child to a parent using refs and portals in React
- React BrowserRouter - how to programmatically navigate to different routes?
- Is it possible to selectively pass DOM events through overlapping canvases?
- How do I scroll into a item in a list by search operation using react?
- Identifying image presence in react
- How to Convert File Image to Byte[] ReactJS?
- How do you prevent the back and forward broswer buttons from causing the page to reload and drop state when canceling navigation. React-router v4.3
- Preload Images from URL React
- My react app not running in IE11 after migrated Webpack from v4 to v5
- Render elements after input search and onClick
- Jest/Enzyme test React component with async/await method in try/catch
- How to set a state variable in the parent of a React Route?
- React-native programmatically scrolling multiline TextInput
- TypeError: Cannot read property 'first_name' of null
- How to go to last element in react?
- How to remove last divider from the list in Grid system in Material Ui
- Having issues using Pick utility type with React useState hook
- Best method to combine defined props in React component
- How to change the value of input to subscript?
- get notified when result of useContractCall from useDapp arrives in react hook?
- Cannot fetch properly data from API
- Swiperjs in React : swiper.slideTo TypeScript
- How to convert pagination numbers to arabic numbers?
- Node.js Cannot Find Module error on npm start
- use ReactJS to .map through response of Express API
- Submitting multiple input fields with same field name- ReactJs
- How to style components using makeStyles and still have lifecycle methods in Material UI?
- reactjs/laravel 'npm run development' fails with syntax error 'Unexpected Token'
- Attempted import error: 'HelpBlock' is not exported from 'react-bootstrap'