如果你想使用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指南與你有關。
我按照你的說法完成了項目,看起來都很好,但是如何才能以用戶身份「登錄」呢? –