所以我有一个登录的Spring启动应用程序。在我的应用程序中,有三种不同的角色:ROLE_ADMIN
,ROLE_USER
,ROLE_TEACHER
当有人注册帐户时,默认角色为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);
}
在网站上执行某项操作时,用户角色将更改为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";
}
现在是我的问题的线索。我有一个页面,只有ADMIN用户才能访问。所以我配置了 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();
}
但在使用ROLE_USER
和USER_ADMIN
的两位用户访问/ adminpage时,我收到错误消息:
出现意外错误(type = Forbidden,status = 403)。访问是 拒绝
为什么hasAuthority("ROLE_ADMIN")
或hasRole("ADMIN")
对管理员用户不起作用?