我的应用程序是一个完整的Restful样式Web应用程序,仅提供JSON接口(没有网页)。我想编写自己可以完全控制登录过程的控制器:
@GetMapping("/login")
public String login(@RequestParam String username,
@RequestParam String password,
HttpServletRequest req,
HttpServletResponse resp) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(username, password);
try {
Authentication auth = authManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (AuthenticationException ex) {
return ex.getMessage();
}
return "success";
这是我的UserDetailsService
:
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
if (!name.equals("whf")) {
throw new UsernameNotFoundException("not found");
}
// load roles
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("admin"));
return new User("whf", "pwd", authorities);
}
}
但是,当我访问需要admin
角色的URL时,我得到了Access is Denied
:
@GetMapping("/a")
@PreAuthorize("hasRole('admin')")
public String A(Principal principal) {
return "a";
}
当前用户已获得admin
角色。为什么我无法访问/a
?
我已经弄清楚了。我错过了授予授权的步骤中的ROLE_
前缀。