如果你想使用Spring Security来保护您的应用程序访问用户ID 2S'的书签,您可以创建自定义UserDetailsService
读取用户数据从DB每个请求。东西是这样的:
@Component
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
protected UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException(String.format("User with email=%s was not found", email));
}
return user;
}
}
当然,假设你有JPA的实体,称为User
实现的UserDetails接口
有了这个机制,你可以注入User
实例为MVC控制器:
@GetMapping("/bookmarks")
public List<Bookmark> readBookmarks(Principal principal) {
User user = (User) principal;
// read bookmarks code
}
您可以在应用程序通过也被读入的任何地方:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
User user = (User) principal;
反应简评:
这是一个很大的决定作出广泛的话题。例如您可以考虑使用JWT,OAUTH2或基于令牌的身份验证。如果你从Spring Security开始,我推荐看看他们的Guides section。尤其是Spting MVC指南与你有关。
我按照你的说法完成了项目,看起来都很好,但是如何才能以用户身份“登录”呢? –