title: Django's Custom Authentication Middleware & Authentication Backend
body: <p>I'm writing a custom Authentication middleware that check the incoming requests for the &quot;Authorization&quot; key in the header, which contains a token.</p>
  <p>I'm using this token to check with a third-party (Microsoft Graph) for the validity of the user. MS Graph will respond with an object like below</p>
  <pre><code># the response object
  
  {
      '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users/$entity',
      'businessPhones': ['xxx'],
      'displayName': 'xxx',
      'givenName': 'xxx',
      'id': 'xxx',
      'jobTitle': None,
      'mail': 'xxx',
      'mobilePhone': None,
      'officeLocation': None,
      'preferredLanguage': 'xxx',
      'surname': 'xxx',
      'userPrincipalName': 'xxx'
  }
  </code></pre>
  <p>EDIT: Adding custom middleware code here:</p>
  <pre class="lang-py prettyprint-override"><code>class AuthenticationMiddleware(MiddlewareMixin):
      if not request.user.is_authenticated:
          if &quot;Authorization&quot; in request.headers:
              # Make a request to MS Graph with the given token
              # to get user details and append to request
              token = request.headers[&quot;Authorization&quot;]
          elif &quot;accessToken&quot; in request.GET:
              token = request.GET[&quot;accessToken&quot;]
          else:
              token = None
  
          if token:
              url = &quot;https://graph.microsoft.com/v1.0/me/&quot;
              payload = {}
              headers = {&quot;Authorization&quot;: &quot;Bearer {}&quot;.format(token)}
              response = requests.request(&quot;GET&quot;, url, headers=headers, data=payload)
              if response.ok:
                  request.custom_user = response.json()
              else:
                  request.custom_user = AnonymousUser
          else:
              request.custom_user = AnonymousUser
  
  </code></pre>
  <p>Now I want to design this to work just like Django's default authentication backend with proper group and permission. How can I work on a LazyObject to be able to check for user's group membership and permission?</p>
  <p><strong>UPDATE</strong></p>
  <p>It looks like there's also a custom backend authentication that works like this.</p>
  <p>Is it doing the same thing as I'm doing with the middleware?</p>
  <pre class="lang-py prettyprint-override"><code>from django.contrib.auth.backends import BaseBackend
  
  class MyBackend(BaseBackend):
      def authenticate(self, request, token=None):
          # Check the token and return a user.
          ...
  </code></pre>