title: Preventing HTTP Basic Auth Dialog using AngularJS Interceptors
body: <p>I'm building an AngularJS (1.2.16) web app with a RESTful API, and I'd like to send 401 Unauthorized responses for requests where authentication information is invalid or not present. When I do so, even with an HTTP interceptor present, I see the browser-presented basic "Authentication Required" dialog when an AJAX request is made via AngularJS. My interceptor runs <em>after</em> that dialog, which is too late to do something useful.</p>
  
  <p><strong>A concrete example:</strong></p>
  
  <p>My backend API returns 401 for <code>/api/things</code> unless an authorization token is present. Nice and simple.</p>
  
  <p>On the AngularJS app side, I've looked at the <a href="https://docs.angularjs.org/api/ng/service/$http#interceptors" rel="noreferrer">docs</a> and set up an interceptor like this in the <code>config</code> block:</p>
  
  <pre><code>$httpProvider.interceptors.push(['$q', function ($q) {
    return {
      'responseError': function (rejection) {
        if (rejection.status === 401) {
          console.log('Got a 401')
        }
        return $q.reject(rejection)
      }
    }
  }])
  </code></pre>
  
  <p>When I load my app, remove the authentication token, and perform an AJAX call to <code>/api/things</code> (to hopefully trigger the above interceptor), I see this:</p>
  
  <p><img src="https://i.stack.imgur.com/FlW9f.png" alt="Authentication Required"></p>
  
  <p>If I cancel that dialog, I see the <code>console.log</code> output of "Got a 401" that I was hoping to see <em>instead of that dialog</em>:</p>
  
  <p><img src="https://i.stack.imgur.com/xDM7g.png" alt="Got a 401"></p>
  
  <p>Clearly, the interceptor is working, but it's intercepting too late!</p>
  
  <p>I see numerous posts on the web regarding authentication with AngularJS in situations just like this, and they all seem to use HTTP interceptors, but none of them mention the basic auth dialog popping up. Some erroneous thoughts I had for its appearance included:</p>
  
  <ul>
  <li>Missing <code>Content-Type: application/json</code> header on the response? Nope, it's there.</li>
  <li>Need to return something other than promise rejection? That code always runs after the dialog, no matter what gets returned.</li>
  </ul>
  
  <p>Am I missing some setup step or using the interceptor incorrectly?</p>