2017-04-24 51 views
1

如何根據與JPA相關聯的mySQL數據庫中的信息輕鬆創建Spring用戶會話?Spring和JPA的RESTfull用戶會話

作爲一個簡單的例子可以說我有2個表:

用戶

  • INT ID
  • VARCHAR(30)的用戶名
  • VARCHAR(20)密碼

書籤

  • INT ID
  • VARCHAR(20)名
  • TEXT desctription
  • INT用戶(FK)

用戶將能夠通過請求觀看他們的書籤以下網址:

http://localhost:8080/bookmarks 

以這種方式,我需要單獨的用戶會話(在這種情況下,身份驗證不是我的主要優先級)才能夠顯示特定於用戶的書籤。

另一種方式去是通過訪問書籤信息:

http://localhost:8080/{userId}/bookmarks 

在這種情況下,我怎麼能阻止用戶訪問其他用戶的書籤信息? (如防止用戶ID 1,從使用url http://localhost:8080/2/bookmarks

回答

1

如果你想使用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指南與你有關。

+0

我按照你的說法完成了項目,看起來都很好,但是如何才能以用戶身份「登錄」呢? –