title: Login to Spring Boot with AngularJS $http.post
body: <p>I have a spring boot application and want to log into it via my angularJS service. I did log in via postman which saves the cookie in my browser, but I want to log in again using my service. Due to my cookie I can call any controllers in my spring boot app ( they all require authentication). But all login requests fail with error 'Unauthorised'. Full browser console output -
  POST <a href="http://localhost:3344/bl/login" rel="nofollow">http://localhost:3344/bl/login</a> 401 (Unauthorized)</p>
  
  <p>Security config for spring ( I extend WebSecurityConfigurerAdapter):</p>
  
  <pre><code>@Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.jdbcAuthentication()
                  .dataSource(dataSource)
                  .passwordEncoder(passwordEncoder())
                  .usersByUsernameQuery(USERS_BY_USERNAME_QUERY)
                  .authoritiesByUsernameQuery(AUTHORITIES_BY_USERNAME_QUERY);
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.csrf().disable()
                      .exceptionHandling()
                      .authenticationEntryPoint(restAuthenticationEntryPoint)
                      .and()
                  .authorizeRequests()
                      .antMatchers("/").authenticated()
                      .and()
                  .formLogin()
                      .loginProcessingUrl("/bl/login")
                      .usernameParameter("user")
                      .passwordParameter("pass")
                      .successHandler(authenticationSuccessHandler)
                      .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                      .and()
                  .logout()
                      .logoutUrl("/logout")
                      .invalidateHttpSession(true);
      }
  </code></pre>
  
  <p>My Angular service is pretty simple:</p>
  
  <pre><code>loginModule.factory('loginService', function($http) {
    return {
      login: function(username, password) {
        $http.post('/bl/login', {user: 'admin', pass: 'admin'}).then(
          function(response) {
            window.alert('success')
          },
          function(response){
            window.alert('fail')
          });
      }
    };
  });
  </code></pre>
  
  <p>I also created a controller as a 'mock' login service to test my angular code:</p>
  
  <pre><code>@RequestMapping(value ="/bl/login2", produces="application/json")
    JSONResponse login(@RequestBody LoginCreds credentials) {
  
      return new JSONResponse("logged in " + credentials.getUser());
    }
  </code></pre>
  
  <p>This controller works and I can see that my login and password are passed correctly and I get the response back to my angular service.
  LoginCreds contains 2 strings 'user' and 'pass'. 
  JSONResponse contains a single string.</p>