graphql-over-http icon indicating copy to clipboard operation
graphql-over-http copied to clipboard

Status codes for unauthenticated OAuth errors

Open tadhglewis opened this issue 1 year ago • 1 comments

Bit of context, I have an authenticated Apollo Server using OAuth.

There is a bit of a conflict between OAuth spec and GraphQL as the OAuth spec recommends returning 401 for unauthenticated/expired tokens but my understanding is the current recommendations for status codes in GraphQL is (almost) always return 200.

GraphQL, by design, does not use the same conventions from REST to communicate via HTTP verbs and status codes. Client information should be contained in the schema or as part of the standard response errors field.

https://www.apollographql.com/docs/apollo-server/data/errors/#returning-http-status-codes

However it seems with the current draft spec here https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md#status-codes, you should be returning status codes.

What are the thoughts around status codes specifically when using OAuth? What status code should unauthenticated errors cause?

tadhglewis avatar Jul 25 '22 23:07 tadhglewis

From the spec:

application/graphql+json

[...] If the client is not permitted to issue the GraphQL request then the server SHOULD reply with 403, 401 or similar appropriate status code.

If authentication fails then this would mean the client is not permitted to issue the GraphQL request.

For application/json media type we generally recommend 200, but it depends on if you are intending to return a GraphQL compliant error response, or just a regular authentication failure response. From the spec:

Note: A status code in the 4xx or 5xx ranges or status code 203 (and maybe others) could originate from intermediary servers; since the client cannot determine if an application/json response with arbitrary status code is a well-formed GraphQL response (because it cannot trust the source) the server must use 200 status code to guarantee to the client that the response has not been generated or modified by an intermediary.

Summary: if you want the client to be able to trust the response is valid GraphQL, you either need to return a 2xx status code, or you need to use the application/graphql+json media type in the response.

benjie avatar Jul 26 '22 07:07 benjie