title: How to proper authenticate an AngularJS client to the server
body: <p>I'm building an AngularJS web-app that uses a RESTful API (Jersey).</p>
  
  <p>On the server side I am using a Java Application Server (in detail Glassfish 4).</p>
  
  <p>My setup is as follows:</p>
  
  <ul>
  <li>AngularJS webapp is deployed as a single war file to the Java EE Application server.</li>
  <li>The RESTfulAPI (and the backend logic) is also deployed as a war file to the same Java EE Application server. </li>
  <li>The AngularJS webapp calls the REST API to get the data it needs.</li>
  <li>The RESTful API:
  <ul>
  <li><code>/api/public/*</code> for public not restricted access (e.g. /api/public/users/signup to register as a new user). Any user is allowed to access this area. No login required</li>
  <li><code>/api/private/*</code> for restricted access (e.g. /api/private/account/{id} to retrieve some account specific data)</li>
  </ul></li>
  <li>The private resources are protected with the Java EE internal security concepts (see below for web.xml details).</li>
  </ul>
  
  <p><strong>Web.xml</strong></p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;security-constraint&gt;
      &lt;web-resource-collection&gt;
          &lt;web-resource-name&gt;PRIVATE REST API&lt;/web-resource-name&gt;
          &lt;url-pattern&gt;/private/*&lt;/url-pattern&gt;
          &lt;http-method&gt;GET&lt;/http-method&gt;
          &lt;http-method&gt;POST&lt;/http-method&gt;
          &lt;http-method&gt;HEAD&lt;/http-method&gt;
          &lt;http-method&gt;PUT&lt;/http-method&gt;
          &lt;http-method&gt;OPTIONS&lt;/http-method&gt;
          &lt;http-method&gt;TRACE&lt;/http-method&gt;
          &lt;http-method&gt;DELETE&lt;/http-method&gt;
      &lt;/web-resource-collection&gt;
      &lt;auth-constraint&gt;
          &lt;description&gt;Have to be a USER&lt;/description&gt;
          &lt;role-name&gt;USERS&lt;/role-name&gt;
      &lt;/auth-constraint&gt;
  &lt;/security-constraint&gt;
  &lt;login-config&gt;
      &lt;auth-method&gt;BASIC&lt;/auth-method&gt;
      &lt;realm-name&gt;userauth&lt;/realm-name&gt;
  &lt;/login-config&gt;
  &lt;security-role&gt;
      &lt;description/&gt;
      &lt;role-name&gt;USERS&lt;/role-name&gt;
  &lt;/security-role&gt;
  </code></pre>
  
  <p>This setup works for me, but only if I invoke the URLs manually in the browser.
  If I am not authenticated and address a secured area, the browser asks for username and password. If the provided credentials are valid, I from there on have access to the restricted area: Fine.</p>
  
  <p>But how do I get that working with AngularJS?
  To login there is a POST API call: <code>/api/public/users/login</code> where you have to provide credentials from a form (username and password). </p>
  
  <p>The client side code is:</p>
  
  <pre><code>ctrls.controller('LoginController', function($scope, $http, $log, $location, UserService, RemoteServerHelperService) {
      $scope.loginDataWrong = undefined;
      $scope.login = function(credentials) {
      $http.post(RemoteServerHelperService.buildURL('/public/users/login'), credentials)
          .success(function (data, status) {
              UserService.setLoggedIn(credentials.email);
              $scope.loginDataWrong = undefined;
              $location.path('/app');
              $log.info("login attempt: successfull. User.loggedIn:" + UserService.isLoggedIn());
          }).error(function (data, status, headers, config) {
              UserService.invalidate();
              $scope.loginDataWrong = true;
              $log.info("login attempt: failed. User.loggedIn:" + UserService.isLoggedIn());
          });
      };
  });
  </code></pre>
  
  <p>The client side code seems to work. I also have some routes in place to secure content on the client side, and so on. There are several posts out there which describe the client side code in detail. So this "snippet" should be enough. </p>
  
  <p>The server side code is:</p>
  
  <pre><code>@POST
  @Path("/login")
  @Consumes(MediaType.APPLICATION_JSON)
  public Response login(Credentials credentials, @Context HttpServletRequest request) {
      if (isAlreadyAuthenticated(request)) {
          try {
              request.logout();
          } catch (ServletException ex) {
              return Response.status(Status.CONFLICT).build();
          }
      }
  
      // not authenticated
      try {
          request.login(credentials.getEmail(), credentials.getPassword());
          return Response.ok().build();
      } catch (ServletException ex) {
          return Response.status(Status.CONFLICT).build();
      }
  }
  </code></pre>
  
  <p>But however, this does not "authenticate" the client side for further requests. When I make a API call on a restricted area after successfully login I get a <code>403 FORBIDDEN</code> response from the server side. So I assume that I am doing something wrong. Do you have any ideas how to authenticate the client to the server for further requests?</p>
  
  <p>A possible solution could be to switch to FORM-based authentication and simply invoke j_security_check with j_username and j_password, but for now I want to stick with BASIC-Authentication and perform the authentication manually via the RESTful API. </p>
  
  <p>The setting <code>$httpProvider.defaults.withCredentials = true;</code> somehow doesn't seem to have any effect. </p>
  
  <p><strong>Update:</strong></p>
  
  <p>Thanks to the tip of lossleader I solved the problem. 
  I removed the <code>login()</code> method, because I want the Java EE-Server to take care of authentication. </p>
  
  <p>To access secured areas the AngularJS webapp has to set the HTTP-Header correctly. In my case <code>$http.defaults.headers.common['Authorization'] = 'Basic &lt;username:pw&gt;';</code> where <code>username:password</code> has to be Base64 encoded. </p>
  
  <p>After I set the headers correctly, no Password Prompt is shown and the AngularJS webapp can access the REST API.</p>