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??