question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow HTTP401 from "context creation failed" (schema authorization)

See original GitHub issue

Problem

Apollo docs suggest doing “schema authorization” in the context function. However, when you throw an AuthenticationError in the context function, the HTTP status is set to 400 and haven’t found a way to customise this behavior. I’d like a 401 in this situation.

The relevant code can be found from: https://github.com/apollographql/apollo-server/blob/2d1544d049429f979cfcb28c9b83589e23873885/packages/apollo-server-core/src/runHttpQuery.ts#L134-L152

Solution?

Plugins?

Allow a similar solution as described in https://github.com/apollographql/apollo-server/issues/1709#issuecomment-495793375 (requestDidStart + didEncounterErrors)

Customise apollo-server-express behavior?

It seems I should be able to customise behavior at the express<->Apollo level, here: https://github.com/apollographql/apollo-server/blob/bf0cd6b40a639f0453973fdef8c21550b02bb681/packages/apollo-server-express/src/expressApollo.ts#L50-L65

Should full schema auth happen elsewhere?

Different web servers can probably check for auth token / cookie before routing to POST /graphql

Hacky solution for Express


/*
Not included:
- jwt middleware adds req.jwtToken and req.jwtPayload
- apolloServer = new ApolloServer(...)

Note: the order of the three calls here matters.
*/

// before any apollo code, check JWT 
app.post('/graphql', (req, res, next) => {
  if (!req.jwtToken || !req.jwtPayload || !req.jwtPayload.roles.includes('user')) {
    throw new AuthenticationError('unauthorized') // Apollo's error but we could also use our own
  }
  next()
})

apolloServer.applyMiddleware({ app, path: '/graphql' })

// error middleware that handles AuthenticationError by manually constructing a graphql error
app.use((err, req, res, next) => {
  if (err instanceof AuthenticationError) {
    res.status(401).send({
      data: null,
      errors: [
        {
          message: err.message,
          locations: err.locations || [],
          extensions: err.extensions || [],
          path: err.path || [],
        },
      ],
    })
  } else {
    next(err)
  }
})

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:4
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
DavidFlorincommented, Feb 13, 2020

Same problem here. If we do the authorization during the context creation, didEncounterErrors is not called

0reactions
abernixcommented, Dec 31, 2020

Linking this to: #3223

Read more comments on GitHub >

github_iconTop Results From Across the Web

Authentication and authorization - Apollo GraphQL Docs
Before we can correctly control access to data, we have to authenticate a user. There are many patterns for providing authentication credentials, including ......
Read more >
401 Unauthorized - HTTP - MDN Web Docs
The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed ...
Read more >
Apollo GraphQL Playground: 401 Unauthorized - Stack Overflow
You need to enable the same-origin policy. See the GraphQL Playground docs. const server = new ApolloServer({ schema: MySchema, context: ...
Read more >
Authentication and authorization OpenShift Container Platform ...
If you do not present a valid access token or certificate, your request is unauthenticated and you receive an HTTP 401 error. An...
Read more >
Access Token Request Error - TIBCO Product Documentation
The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found