2

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 http://localhost:3344/bl/login 401 (Unauthorized)

Security config for spring ( I extend WebSecurityConfigurerAdapter):

@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);
    }

My Angular service is pretty simple:

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')
        });
    }
  };
});

I also created a controller as a 'mock' login service to test my angular code:

@RequestMapping(value ="/bl/login2", produces="application/json")
  JSONResponse login(@RequestBody LoginCreds credentials) {

    return new JSONResponse("logged in " + credentials.getUser());
  }

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.

1

1 Answer 1

3

Solved it, the problem was that in my spring configuration I have 'formLogin()' that means i have to change the content type header in my request from angular service to 'application/x-www-form-urlencoded'. And serialize the data accordingly. This link explains it with examples.

My end result looks like:

     var req = {
        method: 'POST',
        url: 'bl/login',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: $.param({ user: username, pass: password }),
      };

      $http(req).then(
        function(response) {
          window.alert('success')
        },
        function(response){
          window.alert('fail')
        });
      }

Since angular serializes data to JSON by default we need to use $.param() function for serialization.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.