title: Reading token attached on headers in flask middleware gives "Working outside of request context" error
body: <p>I want to have middleware in my flask application to check for token, i do not want to use decorator, since there are hundreds of url routes.</p>
  <p>middleware.py</p>
  <pre><code>from werkzeug.wrappers import Request, Response
  import logging
  import jwt
  import traceback
  from flask import request
  
  
  class Middleware:
      &quot;&quot;&quot;
      Middleware to check token
      &quot;&quot;&quot;
  
      def __init__(self, app):
          self.app = app
  
      def __call__(self, environ, start_response):
          try:
              token = request.headers[&quot;HTTP_AUTHORIZATION&quot;]
              token_json = jwt.decode(token, &quot;secret_key&quot;, algorithms=['HS256'], audience='account')
              environ['USER_DETAIL'] = token_json
              return self.app(environ, start_response)
  
          except Exception as e:
              logging.info(traceback.print_exc())
              res = Response(u'{}'.format(e), mimetype='text/plain', status=401)
              return res(environ, start_response)
  </code></pre>
  <p>this throws and error on line <code>token = request.headers[&quot;HTTP_AUTHORIZATION&quot;]</code></p>
  <pre><code>Traceback (most recent call last):
    File &quot;flask_service/middleware.py&quot;, line 20, in __call__
      token = request.headers[&quot;HTTP_AUTHORIZATION&quot;]
    File &quot;/usr/local/lib/python3.7/site-packages/werkzeug/local.py&quot;, line 348, in __getattr__
      return getattr(self._get_current_object(), name)
    File &quot;/usr/local/lib/python3.7/site-packages/werkzeug/local.py&quot;, line 307, in _get_current_object
      return self.__local()
    File &quot;/usr/local/lib/python3.7/site-packages/flask/globals.py&quot;, line 37, in _lookup_req_object
      raise RuntimeError(_request_ctx_err_msg)
  RuntimeError: Working outside of request context.
  </code></pre>
  <p>I tried <code>environ[&quot;HTTP_AUTHORIZATION&quot;]</code> it gives <code>key error</code> since HTTP_AUTHORIZATION key is not present.</p>
  <p>How do i check for token passed in request header in middleware. Please help me solve this.</p>
  <p>Thanks in advance!</p>