I'd like to seek assistance on how to implement authorization in the Apollo server to restrict immediate access to the payload result. I've searched on Google and other dev forums, but I couldn't find anything. Thank you.
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
csrfPrevention: true,
cache: "bounded",
async onHealthCheck() {
try {
const healthInfo = {
uptime: process.uptime(),
memoryUsage: process.memoryUsage(),
cpuUsage: process.cpuUsage(),
nodeVersion: process.version,
timestamp: new Date()
};
return healthInfo;
} catch (error) {
throw new Error('An error occurred while getting health info');
}
},
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
config.NODE_ENV === "PROD"
? ApolloServerPluginLandingPageDisabled()
: config.NODE_ENV === "STAGE"
? ApolloServerPluginLandingPageProductionDefault({
graphRef: "my-graph-id@my-graph-variant",
footer: false,
})
: ApolloServerPluginLandingPageLocalDefault({ footer: false }, {embed : true}),
// ApolloServerPluginInlineTrace({
// includeErrors: { transform: (err) => (err.message.match(SENSITIVE_REGEX) ? null : err) },
// }),
],
});
const corsOptions = {
origin: "*",
credentials: true,
optionSuccessStatus: 200,
};
const conditionalJwtCheck = async (req, res, next) => {
if (config.ENABLE_API_SECURITY) {
jwtCheck(req, res, next);
} else {
next();
}
};
app.use(cors(corsOptions));
app.use(graphqlUploadExpress());
app.use(
"/graphql",
//cors(corsOptions),
json({ limit: config.PAYLOAD_LIMIT }), // Adjust limit based on your requirements
express.json({ limit: config.PAYLOAD_LIMIT }), // Adjust limit based on your requirements
speedLimiter,
express.urlencoded({ extended: true }),
conditionalJwtCheck,
expressMiddleware(server, {
context: async ({ req , res }) => {
try {
const token = req.headers.authorization || "";
await auditProcessor.auditLogInput(req, res);
return { token };
} catch (error) {
console.error('An error occurred:', error);
}
},
})
);
I'd like to set a header for authorization first before accessing the mutations or queries.