cannot get userinfo from apollo-server-express + subscription #6133
-
Hello, I have some problem that i have jwt authentication using graphql and when signin and paste in playground http headers and passing a token into server in context it return null. Im using apollo-server-express but when using apollo-server it actually work and return a user from jwt verify my server.ts // will using apollo-server-express in production later but in dev we using apollo-server
import { typeDefs } from "./graphql/schema";
import { getUserFromToken } from "./utility/getUserFromToken";
import { createServer } from "http";
import { execute, subscribe } from "graphql";
import { SubscriptionServer } from "subscriptions-transport-ws";
import { makeExecutableSchema } from "@graphql-tools/schema";
import { ApolloServer } from "apollo-server-express";
import { prisma } from "./lib/prisma";
import { Context } from "@interface/db";
import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";
import express from "express";
import * as AllObj from "./services/index";
(async function () {
const app = express();
const httpServer = createServer(app);
const schema = makeExecutableSchema({
typeDefs,
resolvers: {
...AllObj,
},
});
const subscriptionServer = SubscriptionServer.create(
{
schema,
execute,
subscribe,
async onConnect(connectionParams, webSocket, context) {
const token = connectionParams.token;
const userInfo = await getUserFromToken(token);
return console.log(userInfo);
},
},
{ server: httpServer, path: "/graphql" }
);
const server = new ApolloServer({
schema,
context: async ({ req }): Promise<Context> => {
// get user token and user.id from jwt bearer token
const userInfo = getUserFromToken(req.headers.authorization);
console.log(req.headers.authorization);
return {
db,
userInfo,
};
},
plugins: [
{
async serverWillStart() {
return {
async drainServer() {
subscriptionServer.close();
},
};
},
},
ApolloServerPluginLandingPageGraphQLPlayground(),
],
introspection: true,
});
await server.start();
server.applyMiddleware({ app });
const PORT = process.env.PORT || 4000;
httpServer.listen(PORT, () =>
console.log(`🚀 Server is now running on http://localhost:${PORT}/graphql`)
);
})();
export const db = prisma; my getUserfromToken import JWT from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET as string;
export const getUserFromToken = (token: string) => {
try {
return JWT.verify(token, JWT_SECRET) as {
userId: number;
username: string;
};
} catch (error) {
return null;
}
}; Promise Context import { Prisma, PrismaClient } from "@prisma/client";
export interface Context {
db: PrismaClient<
Prisma.PrismaClientOptions,
never,
Prisma.RejectOnNotFound | Prisma.RejectPerOperation | undefined
>;
userInfo: {
userId: number;
username: string;
} | null;
} it confused me, why? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Oh my god This caused in getUserFromToken.ts that my jwt_secret from .env didnt read and returning null when im console that. updated getUserFromToken import JWT from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET || "secret";
export const getUserFromToken = (token: string) => {
try {
return JWT.verify(token, JWT_SECRET) as {
userId: number;
username: string;
};
} catch (error) {
return null;
}
}; hmmm weird |
Beta Was this translation helpful? Give feedback.
Oh my god
This caused in getUserFromToken.ts that my jwt_secret from .env didnt read and returning null when im console that.
Its weird so i adding operator OR
updated getUserFromToken
hmmm weird