Home > Mobile >  In Spring Security config Urls which are permitted for all are not accessable and redirecting to log
In Spring Security config Urls which are permitted for all are not accessable and redirecting to log

Time:10-29

In the configuration below I think I have not done anything wrong. The Urls that I have allowed for all are redirecting me to login page. Same problem with users having role USER.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/**").hasRole("ADMIN")
                .antMatchers("/new/**", "/edit/**", "/create/**", "/save/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/", "/registration/**", "/view/**",).permitAll()
                
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .defaultSuccessUrl("/")
                .and()
                .logout().invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/loggingOut").permitAll();
    }

If you can provide any resource which can help to understand better. I am new to spring, any help would be much appreciated.

CodePudding user response:

I think the problem is with your Role Hierarchy. Try this.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/new/**", "/edit/**", "/create/**", "/save/**").hasAnyRole("USER", "ADMIN")
            .antMatchers("/", "/registration/**", "/view/**",).permitAll()
            .antMatchers("/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/")
            .and()
            .logout().invalidateHttpSession(true)
            .clearAuthentication(true)
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/loggingOut").permitAll();
}

If this did not work please try with different combinations. This article explains the Role Hierarchy, It can help you.

  • Related