title: Authentication verification in Python based GraphQL Server using FastAPI
body: <p>I am having trouble implementing authentication verification in an GraphQL Server built with FastAPI. Before, we were using REST but now we are switching to GraphQL and I am wondering how I can implement this. Before, we had different routers and with FastAPI it is easy to check authentication based on routes using dependencies as in <a href="https://fastapi.tiangolo.com/tutorial/dependencies/" rel="noreferrer">here</a>. We are sending a Token in the Authorization Header which we are decoding in the backend and getting back the user_id which we can then use in our different endpoints.</p>
  <p>I am wondering how this might work using GraphQL here. We use the <a href="https://graphene-python.org/" rel="noreferrer">Graphene</a> and I had a look at <a href="https://www.starlette.io/authentication/" rel="noreferrer">Starlettes Authentication Examples</a> as well as there intro into setting up <a href="https://www.starlette.io/graphql/" rel="noreferrer">GraphQl</a></p>
  <pre><code>import binascii
  from fastapi import FastAPI
  from starlette.authentication import (
      AuthenticationBackend, AuthenticationError, SimpleUser, AuthCredentials
  )
  from starlette.graphql import GraphQLApp
  from starlette.middleware import Middleware
  from starlette.middleware.authentication import AuthenticationMiddleware
  
  from schemas.root import my_schema
  
  
  class BasicAuthBackend(AuthenticationBackend):
      async def authenticate(self, request):
          if &quot;Authorization&quot; not in request.headers:
              raise AuthenticationError('No auth credentials')
  
          auth = request.headers[&quot;Authorization&quot;]
          try:
              id_token = auth.split('Bearer ')[1]
              decoded_token = auth.verify_id_token(id_token)
  
          except (ValueError, UnicodeDecodeError, binascii.Error) as exc:
              raise AuthenticationError('Invalid basic auth credentials')
  
          user_id = decoded_token['uid']
          return AuthCredentials([&quot;authenticated&quot;]), user_id
  
  
  middleware = [
      Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())
  ]
  
  my_schema = Schema(
      query=RootQuery,
      mutation=RootMutation,
  )
  
  api = FastAPI(title=f&quot;MyGraphQLServer&quot;, middleware=middleware)
  api.add_route(&quot;/graphql&quot;, GraphQLApp(schema=my_schema))
  </code></pre>
  <p>For example, imagine that I now would only like to authenticate mutation Requests but not query requests. Furthermore I want to access the user_id in each of my resolvers. What would be the best way to do this?</p>