0

Developing app on Angular.js with Spring Security. I am not able to send the username and password from UI to spring security. Getting null pointer exception. After debugging found that, username is null. Searched a lot on google but not able to fix it. When I click on login button, the debugger takes me to the userdetailserviceimpl.java class and found that username is null. In normal case if I am using spring security login form, if I submit the form with wrong credentials username is not coming null but with ajax call from UI it is coming null.

SecurityConfig.java

@Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
    builder.userDetailsService(userDetailServiceImpl);          
}

@Override
protected void configure(HttpSecurity http) throws Exception {


http
.authorizeRequests()
    .antMatchers("/app/**").permitAll()
    .antMatchers("/login.html").permitAll()
    .anyRequest().authenticated()
    .and()
    .exceptionHandling()
        .authenticationEntryPoint(unauthorisedHandler)
        .accessDeniedHandler(accessDenied)
        .and()
.formLogin()
.loginProcessingUrl("/authenticate")
    .successHandler(authSuccess)
    .usernameParameter("username")
    .passwordParameter("password")
    .permitAll()
    .and()
    .logout().logoutSuccessHandler(logoutSuccess).permitAll()
    .and()
    .csrf().disable();      

}

UserDetailServiceImpl.java

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginDao loginDao;

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        UserInfo userInfo = loginDao.loadUserByUsername(username);
        System.out.println(userInfo.getUserName() + "" + userInfo.getRole());
        GrantedAuthority authority = new SimpleGrantedAuthority(userInfo.getRole());
        UserDetails userDetails = (UserDetails)new User(userInfo.getUserName(), userInfo.getPassword(), Arrays.asList(authority));
        return userDetails;
    }

}

login.controller.js

var vm = this;
    vm.credentials = {};

    vm.login = function(){
        var config = {
                params: {
                 username: vm.credentials.username,
                 password: vm.credentials.password,
                }
               };
        loginService.login(config);
    };

login.service.js

this.login = function(config){
    return ajaxService.login("../authenticate",config);
};

common ajax service

this.login = function (url, dataObj) {

        var res = $http({
            url: url,
            method: 'POST',
            data: dataObj,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'XMLHttpRequest'
              }
        });

        res.success(function(data, status, headers, config) {

        });
        res.error(function(data, status, headers, config) {

        });
        return res;
    };

login.html

<div ng-controller='LoginController as lc'>

<form>
    <div class="form-group"
         ng-class="{'has-error is-focused' : authenticationError}">
        <input id="login" ng-model="lc.credentials.username" type="text" class="form-control"
               required="required" placeholder="login"/>
        <span ng-show="authenticationError" class="help-block">
            Please check your credentials and try again.
        </span>
    </div>

    <div class="form-group">
        <input id="password" ng-model="lc.credentials.password" type="password" class="form-control"
               required="required" placeholder="password"/>
    </div>

    <input type="checkbox" ng-model="rememberMe"/><span> Remember me</span>

    <button ng-click="lc.login()" >Login</button>
</form>
</div>

Update for stack trace

Nov 22, 2016 12:47:16 AM org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter doFilter
SEVERE: An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at com.er4u.core.login.service.impl.UserDetailServiceImpl.loadUserByUsername(UserDetailServiceImpl.java:30)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
    ... 37 more
3
  • @Mr.7 setting username and password in html page in credentials model Commented Nov 21, 2016 at 5:55
  • 1
    I guess this is due to extra keys in dataObj sent in the request. Can you try removing params: from request object and directly add username and password in the object?
    – Harry Joy
    Commented Nov 21, 2016 at 6:10
  • @HarryJoy - thanks for the suggestion but I already applied this and its not working. Commented Nov 21, 2016 at 6:17

2 Answers 2

0

You're using a wrapper object, while Spring is just expecting the username and password in an object. Change var config = { params: { username: vm.credentials.username, password: vm.credentials.password}}; to var config = {username: vm.credentials.username, password: vm.credentials.password. Also, there is a tutorial that shows you exactly how to do this with simplicity:

https://spring.io/guides/tutorials/spring-security-and-angular-js/

11
  • I have also tried this but getting username null in userdetailserviceimpl.java class Commented Nov 21, 2016 at 6:33
  • try to use chrome debugger and see the information sent to the server.
    – Haim Raman
    Commented Nov 21, 2016 at 6:49
  • @HaimRaman - Yes, I debug it using chrome debugger and information is sending perfectly fine. Commented Nov 21, 2016 at 6:55
  • @VaibhavDalela Okay, so the username exists in the payload object, but you're getting a null pointer exception server-side? Can you post the stack trace of the error?
    – Trevor Bye
    Commented Nov 21, 2016 at 14:39
  • @J.West - added stack trace. Commented Nov 21, 2016 at 19:10
0

Finally I solved the issue by changing

var config = {
                params: {
                 username: vm.credentials.username,
                 password: vm.credentials.password,
                }
               }; 

to

vm.user = "username="+vm.credentials.username+"&password="+vm.credentials.password;

Thanks everyone for helping. Hope this answer will help others in future. :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.