0

This is my security config in my springboot application

package com.logan.cricketbeting.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.logan.cricketbeting.Service.CustomUserDetailsService;
import com.logan.cricketbeting.Service.UserServiceImpl;

//security configuration class for implementing spring security on urls
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;
    //for handling user success handler
    @Autowired
    private CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
    @Override
    //this configuration is for handling user requests
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
            .antMatchers("/orders").permitAll()
                 .antMatchers("/login").permitAll()
                 .antMatchers("/admin/**").hasAuthority("admin")
                 .antMatchers("/distributor/**").hasAuthority("distributor")
                 .antMatchers("/user/**").hasAuthority("user").anyRequest()
                .authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
                .loginPage("/login").failureUrl("/login?error=true")
                .usernameParameter("username")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login").and().exceptionHandling().accessDeniedPage("/403");
    }

    //this method allows static resources to be neglected by spring security
    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/assets/**","/fonts/**","/vendor/**");
    }

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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         //BCryptPasswordEncoder encoder = passwordEncoder();
        //auth.inMemoryAuthentication().withUser("logan@yahoo.com").password(encoder.encode("admin")).roles("user");
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}


}

And this is my customsuccess handler

package com.logan.cricketbeting.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


/*
 * This is an Authentication Success handler class for handling what happens after the user is suc
 * successfully logined in the application
 * 
 * 
 * 
 * */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //set our response to OK status
        response.setStatus(HttpServletResponse.SC_OK);
//this check granted authorities against the username
        for (GrantedAuthority auth : authentication.getAuthorities()) {
            //if the granted authority is user then it is allowed

            //if its admin it is allowed 

             if("admin".equals(auth.getAuthority())) {
                response.sendRedirect("/admin/home"); //working fine
            }

            else if("distributor".equals(auth.getAuthority())) {
                response.sendRedirect("/distributor/home");//working fine
            }

            else if ("user".equals(auth.getAuthority())) {
                    response.sendRedirect("/user/home");//it is not working
                }

            //else it redirects to the 403 forbidden error
            else {
                response.sendRedirect("/403");
            }
        }
    }


}

My admin and distributor url is working fine after login but the user one gives an error

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

I dont where is the glitch ,any idea how to solve this???

  • 1
    have a look at https://stackoverflow.com/questions/2123514/java-lang-illegalstateexception-cannot-forward-sendredirect-create-session –  Aug 26 '18 at 07:48
  • yes I saw that ,but then why other two redirects are working except this? –  Aug 26 '18 at 07:51
  • What authorities has your user? Your coode should fail, if one user has more than one authority. – dur Aug 26 '18 at 07:58
  • You already said, that you read the link weizenkeim hugo posted. That's the reason. – dur Aug 26 '18 at 08:04
  • 1
    oh ok got it !! it checks for role and if there are multiple role then it send headers cool .thanks –  Aug 26 '18 at 08:06

1 Answers1

0

if the user has multiple authorities your code code calls sendRedirect multiple times. Adding a break or return after each sendRedirect should solve the issue.

  • Don't answer a duplicate, just flag the question. You already commented the link of the dupe target. – dur Aug 26 '18 at 08:10