title: Inject additional parameter in request using FastAPI
body: <p>I'm creating an API gateway using <code>fastAPI</code> for some microservices, which in I authenticate user via Azure AD via <a href="https://github.com/Intility/fastapi-azure-auth" rel="nofollow noreferrer">fastapi-azure-auth</a>.
  So I'm trying to take out the user info from the <code>request</code> object (<code>request.state.user</code>) and inject my own token in it to later pass to other microservices.</p>
  <p>I tried using <a href="https://fastapi.tiangolo.com/tutorial/middleware/" rel="nofollow noreferrer">app.middleware</a>,</p>
  <pre><code>@app.middleware(&quot;http&quot;)
  async def add_process_time_header(request: Request, call_next):
      new_token = generate_token(request.state.user)
      request[&quot;new_token&quot;] = new_token
      response = await call_next(request)
      return response
  </code></pre>
  <p>but I'm getting following error at the initialization of the project:</p>
  <blockquote>
  <p>AttributeError: 'State' object has no attribute 'user'</p>
  </blockquote>
  <p>Also I tried creating a decorator:</p>
  <pre><code>from functools import wraps
  
  def token_injector(function):
      @wraps(function)
      def wrap_function(*args, **kwargs):
          user: User = kwargs['request'].state.user
          new_token = generate_token(user)
          kwargs[&quot;new_token&quot;] = new_token # or kwargs['request'][&quot;new_token&quot;] = new_token
          return function(*args, **kwargs)
      return wrap_function
  </code></pre>
  <p>and for this approach, I'm getting these errors:</p>
  <blockquote>
  <p>ValueError: [TypeError(&quot;'coroutine' object is not iterable&quot;),
  TypeError('vars() argument must have <strong>dict</strong> attribute')]</p>
  </blockquote>
  <p>and</p>
  <blockquote>
  <p>TypeError: 'Request' object does not support item assignment</p>
  </blockquote>
  <p>So does anyone have a solution for this?</p>
  <p><strong>UPDATE</strong></p>
  <p>Seems like it can't be done in middleware, cause the user info is added after it</p>