Ateeb Khan
Ateeb Khan

Reputation: 5

Page Redirection Issue in Spring Boot Security

I want to redirect page according to roles. But it's not working.

This is my WebSecurityConfig

@Configuration

@EnableWebMvcSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.jdbcAuthentication().dataSource(dataSource)

     .usersByUsernameQuery(
            "select username,password,role from user where username=?")
        .authoritiesByUsernameQuery(
            "select username, role from user where username=?");

    }   

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

      http

      .authorizeRequests()

        .antMatchers("/hello").access("hasRole(1)")
        .antMatchers("/demo").access("hasRole(2) or hasRole(1)")
        .anyRequest().permitAll()
        .and()
         .formLogin().loginProcessingUrl("/login")
      .loginPage("/login")

      .usernameParameter("username").passwordParameter("password")
      .successHandler(authenticationSuccessHandler)
      .and() 

          .logout().logoutSuccessUrl("/login?logout")   
         .and()
         .exceptionHandling().accessDeniedPage("/403")
        .and()
          .csrf();

    }

}

This is my MvcConfig

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");

        registry.addViewController("/").setViewName("home");
        //registry.addViewController("/").setViewName("hello");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
        //registry.addViewController("/demo").setViewName("demo");
        registry.addViewController("/demoPage").setViewName("demoPage");
        registry.addRedirectViewController("/demo", "demo");
        registry.addViewController("/403").setViewName("403");
    }

    @Bean(name = "dataSource")
    public DriverManagerDataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/userbase");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("yungry");
        return driverManagerDataSource;
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

}

This is my AuthenticationSuccessHandler Class

@Configuration

public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Bean(name = "authenticationSuccessHandler")
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
        // Get the role of logged in user
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String role = auth.getAuthorities().toString();
        System.out.println(role+"");
        String targetUrl = "";
        if(role.contains("1")) {
            targetUrl = "/hello";
        } else if(role.contains("2")) {
            targetUrl = "/demo";
        }
        return targetUrl;
    }
}

Here I want redirect /hello page for role 1 after login and /demo page for role 2 after login but it it's not working, it redirects to /home page.

Upvotes: 0

Views: 908

Answers (1)

ZIANE Mohamed
ZIANE Mohamed

Reputation: 71

your configuration seemes ok, just check if role's name start with the prefix "ROLE_" in database, for your case "ROLE_1" or "ROLE_2".

spring security looks for the prefix "ROLE_" on the attribute by default, so you make sure that your roles have this prefix.

Upvotes: 2

Related Questions