简体   繁体   中英

How to validate token from Localstorage and return currentUser from Apollo Server to React front-end?

I already have a jwt middleware which verifies token and returns currentUser to React front-end:

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null") {
        try{
            const currentUser = await jwt.verify(token, process.env.SECRET)
        } catch {
        console.error(err);
    }
}
next();
});

Now, I want to integrate the logic into the following Apollo server:

const app = express();
const server = new ApolloServer({
  typeDefs: gql(typeDefs),
  resolvers,
  context: async () =>({ 
  db,
  secret: process.env.SECRET,
  }),
});

app.use(cors(corsOptions));
server.applyMiddleware({ app });

At the end, the value of currentUser should be available to be used at react front-end.
How can I achieve this?

You can add the currentUser to the request object inside the middleware. Next, you pass it copy it from the request to the GraphQL context. Then you can add a currentUser resolver and simply return the user from the context.

Your middlware

app.use(async (req, res, next) => {
    const token = req.headers['authorization'];
    if(token !== "null") {
        try{
            req.currentUser = await jwt.verify(token, process.env.SECRET)
        } catch {
        console.error(err);
    }
}
next();
});

Your server

const app = express();
const server = new ApolloServer({
  typeDefs: gql(typeDefs),
  resolvers,
  context: ({ req }) =>({ 
    currentUser: req.currentUser,
    db,
    secret: process.env.SECRET,
  }),
});

app.use(cors(corsOptions));
server.applyMiddleware({ app });

and the resolvers

const resolvers = {
  Query: {
    currentUser: (parent, args, context) => context.currentUser,
    ...
  }
}

Add the corresponding type definition and you should be able to query the current user from your client.

If you need more information here is a detailed tutorial which might be of help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM