SpringSecutity的配置:https://blog.csdn.net/victoyr/article/details/88419070
常用注解
@PreAuthorize(“hasAuthority(‘ROLE_ADMIN’)”) // 指定角色权限才能操作方法 ,比如只有管理员才能访问,或者只有vip用户才能访问
@RestController
@RequestMapping("/users")
@PreAuthorize("hasAuthority('ROLE_ADMIN')") // 指定角色权限才能操作方法
public class UserController {
@Autowired
private UserService userService;
@Autowired
private AuthorityService authorityService;
}
@PreAuthorize(“authentication.name.equals(#username)”)当前认证的用户只能访问自己的资源,比如博客系统中只有自己能访问自己的个人设置界面
@GetMapping("/{username}/profile")
@PreAuthorize("authentication.name.equals(#username)")
public ModelAndView profile(@PathVariable("username") String username, Model model) {
User user = (User)userDetailsService.loadUserByUsername(username);
model.addAttribute("user", user);
return new ModelAndView("userspace/profile", "userModel", model);
}
Spring Security使用一个Authentication对象来描述当前用户的相关信息。SecurityContextHolder中持有的是当前用户的SecurityContext,而SecurityContext持有的是代表当前用户相关信息的Authentication的引用。这个Authentication对象不需要我们自己去创建,在与系统交互的过程中,Spring Security会自动为我们创建相应的Authentication对象,然后赋值给当前的SecurityContext
通过Authentication.getPrincipal()可以获取到代表当前用户的信息,这个对象通常是UserDetails的实例。
// 判断操作用户是否是评论的所有者
String commentOwner = "";
if (SecurityContextHolder.getContext().getAuthentication() !=null && SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
&& !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString().equals("anonymousUser")) {
User principal = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal !=null) {
commentOwner = principal.getUsername();
}
}