title: Using Angular.js - how to serve binary data from a backend that requires authentication?
body: <p>In my angularjs application I am communicating with a backend server that requires basic access authentication via http header. I have implemented the authentication mechanism on the client side as described <a href="http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/" rel="nofollow">here</a>.</p>
  
  <pre><code>angular.module('myAuthModule')
  .config(['$httpProvider', '$stateProvider',
      function ($httpProvider, $stateProvider) {
          $httpProvider.interceptors.push('securityInterceptor');
      }])
  .factory('securityInterceptor', ['$location', '$window', '$q',
      function ($location, $window, $q) {
          return {
              request: function (config) {
                  config.headers = config.headers || {};
                  if ($window.sessionStorage.token) {
                      config.headers['Auth-Key'] = $window.sessionStorage.token;
                  }
                  return config;
              },
              response: function (response) {
                  if (response.status === 401 || response.status === 403) {
                      $location.path('/login');
                  }
                  return response || $q.when(response);
              }
          };
      }
  ]);
  </code></pre>
  
  <p>So far so good, handling xhr requests within the angular app works as expected.</p>
  
  <p>The problem is that I need to provide a download link for pdf documents. My backend server has a <code>/Document/Pdf/:id</code> resource that serves a <code>application/pdf</code> response with <code>ContentDisposition: attachment</code> which also requires authentication. I understand that I cannot initiate a download using xhr, however both providing a link to the document download via <code>ngHref</code> and calling a function that does for example <code>$window.open('/Document/Pdf/13')</code> lead to a <code>401 Unauthorized</code> response by the server.</p>
  
  <p>What am I missing here?</p>