1

So I have a Spring boot application with a login. In my application there are three different roles: ROLE_ADMIN, ROLE_USER, ROLE_TEACHER

When someone registers an account, default role is USER.

UserController.java

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
    userValidator.validate(userForm, bindingResult);

    if (bindingResult.hasErrors()) {
        return "registration";
    }

    userService.save(userForm);

    securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());

    return "redirect:/setup";
}

UserServiceImpl.java

@Override
public void save(User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    if(user.getRoles() == null) {
        Role role = roleRepository.findByName("ROLE_USER");
        user.setRoles(new HashSet<>(Arrays.asList(role)));
    }
    userRepository.save(user);
}

When performing a certain action on the site, the user role is changed to ADMIN.

@RequestMapping(value = "/someaction", method = RequestMethod.POST)
public String makeAdmin(Authentication authentication) {

    User currentUser = userRepository.findByUsername(authentication.getName());
    Role adminRole = roleRepository.findByName("ROLE_ADMIN");
    currentUser.setRoles(new HashSet<>(Arrays.asList(adminRole)));
    userRepository.save(currentUser);
    return "redirect:/webpage";
}

Now comes the clue of my question. I have a page which should be only accessible to ADMIN users. So I configured my WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/resources/**", "/registration").permitAll()
                .antMatchers("/adminpage").hasAuthority("ROLE_ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
}

But when accessing /adminpage for both users with ROLE_USER and USER_ADMIN I get the error:

There was an unexpected error (type=Forbidden, status=403). Access is denied

Why does hasAuthority("ROLE_ADMIN") or hasRole("ADMIN") not work for admin users??

moffeltje
  • 4,521
  • 4
  • 33
  • 57
  • Don't you have to update the users authorities or reauthenticate after role change? – Abu Sulaiman Feb 16 '18 at 20:23
  • @AbuSulaiman Shit I think you're right. I logged out and in again then it worked. Do you know how I can do that programmatically? – moffeltje Feb 16 '18 at 20:32
  • I was looking at this page but i'm not sure if it will work for you. https://stackoverflow.com/questions/9910252/how-to-reload-authorities-on-user-update-with-spring-security – Abu Sulaiman Feb 16 '18 at 20:41
  • @AbuSulaiman Thanks a lot for your time, appreciate it. You put me on the right track. Will try it – moffeltje Feb 16 '18 at 20:51
  • 1
    No problem. While I'm sure you'll figure it out beforehand, I bet someone will come along and provide a clear answer soon. – Abu Sulaiman Feb 16 '18 at 21:04
  • If you get the answer, please post it here. So that it helps others. – Akshatha S R Nov 30 '18 at 06:07
  • Spring likes to automatically prepend ROLE_ on things. This might be your problem--look here fore more info. https://stackoverflow.com/questions/50595519/spring-security-has-simplegrantedauthority-but-hasrole-isnt-working/53373249#53373249 – FlexEast Jun 26 '19 at 15:20

0 Answers0