User account and authorization #8
HowardPWeiss
started this conversation in
General
Replies: 1 comment
-
I fixed this First, I had to set the token in the Authorization HTML header in the GraphQL sandbox I had to call JSON.parse(token) and then pass the parsed token to jwt.verify const getUser = token => { |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have been following the instructions in chapter 7 to implement user accounts and authorization
When I tried to start the ApolloServer per pg 65, the following error was reported
Error: You must
await server.start()
before callingserver.applyMiddleware()
I looked at the web, and I was informed that I needed to user an async function to start the ApolloServer, as follows
async function startApolloServer(typeDefs, resolvers) {
// Same ApolloServer initialization as before
const server = new ApolloServer({
typeDefs,
resolvers,
tracing: true,
context: ({ req }) => {
//console.log(req.headers);
const token = req.headers.authorization;
// try to retrieve a user with the token
const user = getUser(token);
// for now, lets log the user to the console
//console.log("user " + user);
// Add the db models and the user to the context
return { models, user };
}
});
before calling wait server.start();
This works, and I see the message
🚀 Server ready at http://localhost:4000/api
is nodemon, However, I do not see { id: " ....", iat .....) in nodemon after the server running message as illustrated in Figure 7-5
User the Explorer Sandbox, I tried adding a an authentication token using the connections setting dropdown. When I did this, the query failed
Instead, if I added a token in the variables header section of the sandbox main window, the query worked
If I look at the token after const token = req.headers.authorization;,I discover that req.headers,authorization in undefined
If I sent to req.headers to console.log, I see the following
{
host: 'localhost:4000',
'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:98.0) Gecko/20100101 Firefox/98.0',
accept: '/',
'accept-language': 'en-US,en;q=0.5',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
'content-length': '1811',
origin: 'https://studio.apollographql.com',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'cross-site',
connection: 'keep-alive'
}
I do not see the authorization [anywhere]
Index.js per below (with non working ApolloServer start commented out)
const express= require('express');
const { ApolloServer } = require('apollo-server-express');
require('dotenv').config();
//import { ApolloServerPluginInlineTrace } from "apollo-server-core";
const db = require('./db');
const models = require('./models');
// run the server on a port specified in out .env file or port 4000
const port = process.env.PORT || 4000;
const DB_HOST = process.env.DB_HOST;
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const jwt = require('jsonwebtoken');
const getUser = token => {
if (token) {
try {
// return the user information from the token
return jwt.verify(token, process.env.JWT_SECRET);
} catch (err) {
console.log(err);
// if there is a problem with the token, throw an error
throw new Error('Session invalid');
}
}
};
/*
// Apollo Server startup
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
console.log("req: " + req);
// get the token from the headers
const token = req.headers.authorization;
console.log("token: " + token);
// try to retrieve a user with the token
const user = getUser(token);
// for now, lets log the user to the console
console.log("user " + user);
// Add the db models and the user to the context
return { models, user };
}
});
const app = express();
// Apply the Apollo Graphic middleware and set the path tp /api
server.applyMiddleware( { app, path: '/api' });
app.listen(port, () =>
console.log(
GraphQL Server running at http://localhost:${port}${server.graphqlPath}
)
);
*/
async function startApolloServer(typeDefs, resolvers) {
// Same ApolloServer initialization as before
const server = new ApolloServer({
typeDefs,
resolvers,
tracing: true,
context: ({ req }) => {
console.log(req.headers);
const token = req.headers.authorization;
// try to retrieve a user with the token
const user = getUser(token);
// for now, lets log the user to the console
//console.log("user " + user);
// Add the db models and the user to the context
return { models, user };
}
});
// Required logic for integrating with Express
await server.start();
const app = express();
// Connect to the database
db.connect(DB_HOST);
server.applyMiddleware({
app,
});
// Modified server startup
await new Promise(resolve => app.listen({ port: 4000 }, resolve));
console.log(
🚀 Server ready at http://localhost:4000${server.graphqlPath}
);}
startApolloServer(typeDefs, resolvers)
What am I missing?
Howard Weiss
Beta Was this translation helpful? Give feedback.
All reactions