3

I have a problem with roles and authority with my Spring Boot and Spring Security.

I have three possibles roles ("Admin", "Teacher", "Student").

I have this simple classes

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {
        BCryptPasswordEncoder encoder = passwordEncoder();
        http
         .authorizeRequests()
         .antMatchers("/resources/**").permitAll()
         .anyRequest().authenticated()
         .antMatchers("/admin/**").hasAuthority("Admin")    
         .antMatchers("/alumno/**").hasAuthority("Student")
         .antMatchers("/profesor/**").hasAuthority("Teacher")
         .and()
         .formLogin()
         .usernameParameter("email")
         .passwordParameter("password")      
         .loginProcessingUrl("/j_spring_security_check") // Submit URL
         .loginPage("/login").failureUrl("/login?error=true")
         .defaultSuccessUrl("/admin/home")
         .permitAll()
         .and()
         .logout()
         .permitAll();
    }
}

Then, I have the UserDetailsServiceImpl like this (I've put the "Teacher" authority).

@Service
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UsuarioDao usuarioDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

         UsuarioEntity usuarioEntity = usuarioDao.findByUsuario(username);
         Set<GrantedAuthority> grantedAuthorities = new HashSet();
         grantedAuthorities.add(new SimpleGrantedAuthority("Teacher");

        User user = new User(usuarioEntity.getUsuario(),usuarioEntity.getPassword(), grantedAuthorities);
        return user;
    }

}

And then, my Controller:

@RequestMapping(value="/admin/home", method = RequestMethod.GET)
public ModelAndView home(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("adminMessage","Content Available Only for Users with Admin Role");
    modelAndView.setViewName("admin/home");
    return modelAndView;
}

When I login with a user like "Teacher", I can view the /admin/home, I can't understand the problem.

I'll change this one:

 .antMatchers("/admin/**").hasRole("Admin") 
 .antMatchers("/alumno/**").hasRole"Student")
 .antMatchers("/profesor/**").hasRole("Teacher")

And this one:

 grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_Teacher");

I would like when I login with "Teacher" rol the applications give me an error, but I can login to /admin/home so the security is not working.

Any ideas? Thanks

Luisao
  • 455
  • 2
  • 9
  • 20

0 Answers0