我的应用是一个完整的REST风格的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
角色的网址时,我收到了Access is Denied
:
@GetMapping("/a")
@PreAuthorize("hasRole('admin')")
public String A(Principal principal) {
return "a";
}
当前用户已获得admin
角色。为什么我无法访问/a
?
答案 0 :(得分:0)
我已经弄清楚了。
在授予权限的步骤中我错过了ROLE_
前缀。