0

everyone!

I'm having troubles achieving this functionality. I followed all the steps on this post Spring Security and JSON Authentication and read all the links on that post. That's the exact behavior i want to achieve but i keep receiving

username=myUsername&password=myPass.

What am I missing?

I'm really really new at this whole web world thing! if you have any tips or at least tell me what should i be looking for.

Here's my configuration class:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userDetailsService);
        authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public CustomDaoAuthenticationProvider customAuthenticationProvider() {
        CustomDaoAuthenticationProvider customAuthenticationProvider = new CustomDaoAuthenticationProvider();
        customAuthenticationProvider.setUserDetailsService(userDetailsService);
        customAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        return customAuthenticationProvider;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint(){
        return new Http403ForbiddenEntryPoint();
    }

    @Bean
    public CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler(){
        CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler = new CustomAuthenticationSuccessHandler();
        customAuthenticationSuccessHandler.setDefaultTargetUrl("/signin.html");
        customAuthenticationSuccessHandler.setTargetUrlParameter("/home.html");
        return customAuthenticationSuccessHandler;
    }

    @Bean
    public CustomAuthenticationFailureHandler customAuthenticationFailureHandler(){
        CustomAuthenticationFailureHandler customAuthenticationFailureHandler = new CustomAuthenticationFailureHandler();
        customAuthenticationFailureHandler.setDefaultFailureUrl("/signin.html");
        return customAuthenticationFailureHandler;
    }

    @Bean
    public CustomLogoutSuccessHandler customLogoutSuccessHandler(){
        CustomLogoutSuccessHandler customLogoutSuccessHandler = new CustomLogoutSuccessHandler();
        return customLogoutSuccessHandler;
    }

    @Bean
    public CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter() {
        try {
            CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
            customUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
            customUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler());
            customUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler());
            customUsernamePasswordAuthenticationFilter.setFilterProcessesUrl("/j_spring_security_check");
            customUsernamePasswordAuthenticationFilter.setUsernameParameter("username");
            customUsernamePasswordAuthenticationFilter.setPasswordParameter("password");
            return customUsernamePasswordAuthenticationFilter;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/signin.html**").permitAll()
        .antMatchers("/**").authenticated()
        .and().addFilterBefore(new CustomUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
        .logout().permitAll().logoutSuccessUrl("/signin.html").deleteCookies("JSESSIONID").invalidateHttpSession(true).logoutSuccessHandler(customLogoutSuccessHandler())
        .and().exceptionHandling().authenticationEntryPoint(http403ForbiddenEntryPoint())
        .and().csrf().disable();
    }
}

Here's my filter

public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        if ("application/json".equals(request.getHeader("Content-Type"))) {

            StringBuffer sb = new StringBuffer();
            String line = null;
            LoginRequest user = new LoginRequest();
            try {
                BufferedReader reader = request.getReader();
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                String fromBuffer = sb.toString();
                //fromBuffer is reading username=myUsername&password=myPass
                ObjectMapper mapper = new ObjectMapper();
                user = mapper.readValue(fromBuffer, LoginRequest.class);
            } catch (Exception e) {}
            UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken(
                    user.getUsername(), user.getPassword());
            setDetails(request, authenticationRequest);
            return super.attemptAuthentication(request, response);
        } else {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
    }
}

Here's how I'm calling my login service

function doLogin(){
    clearErrorMsg("login-alert");
    var data = new Object();
    data.username = $('#username').val();
    data.username = $('#password').val();
    $.ajax({
        data: data,
        timeout: ajaxTimeout,
        type: 'POST',
        url: rootURL +'/login',
        contentType: "application/json"
    }).done(function(data, textStatus, jqXHR) {
        window.location.href = rootURL + "/home.html";
    }).fail(function(jqXHR, textStatus, errorThrown) {
        displayErrorMsg("login-alert", "Wrong credentials, try again! <br >Error code: [" + errorThrown + "]");
    });
}

Sorry for the long post and thank you for any help you can provide! Maybe the code is a little messy but I've been trying with every solution I've found and none is working for me.

Community
  • 1
  • 1
  • Where are you getting that message appear? In the console/browser? – Aeseir Feb 18 '16 at 02:12
  • In the browser I'm sending {"username":"myUsername","password":"myPass"}, yet, on the server side I'm receiving username=myUsername&password=myPass comming as the request. I don't know if that answers your question – SoManyDoubtsSoLittleTime Feb 18 '16 at 02:16

1 Answers1

0

you keep receiving

username=myUsername&password=myPass.

because some error in javascript code.you should encode data to json string (JSON.stringify(data)) in ajax request

full example

function doLogin(){
    clearErrorMsg("login-alert");
    var data = new Object();
    data.username = $('#username').val();
    data.username = $('#password').val();
    $.ajax({
        data: JSON.stringify(data),
        timeout: ajaxTimeout,
        type: 'POST',
        url: rootURL +'/login',
        contentType: "application/json"
    }).done(function(data, textStatus, jqXHR) {
        window.location.href = rootURL + "/home.html";
    }).fail(function(jqXHR, textStatus, errorThrown) {
        displayErrorMsg("login-alert", "Wrong credentials, try again! <br >Error code: [" + errorThrown + "]");
    });
}
wcong
  • 591
  • 4
  • 8