2012-08-01 94 views
0

我正在開發一個使用Spring MVC的小型應用程序。這是一種廣告牌,用戶可以放置幾種類型的內容。我已經使用security-config.xml爲我的應用(用戶,管理員,匿名)中的不同角色成功配置了安全性。現在你必須登錄發佈,只有管理員用戶可以看到管理面板等。Spring MVC用戶驗證

現在我的問題是,我必須爲每個用戶設置安全性,即用戶修改內容是用戶做了內容。當我調用函數之前,最直接的方法當然是檢查Java,如果用戶登錄和內容的創建者都是相同的。像這樣的東西:

@RequestMapping("/listing/deletecontent.html") 
public String deleteUserContent(@RequestParam String contentId) { 
    //Get the logged user 
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
    User user = userService.loadUserByUsername(userDetails.getUsername()); 

    //Check if the user logged and the content owner are the same 
    if (user == the_user_that_created_the_content) 
      listingService.deleteContent(Integer.valueOf(contentId)); 

    return "redirect:/listing/usercontent.html"; 
} 

我不是爲什麼,但我不喜歡這種方法。它只是在我需要的地方一遍又一遍地「複製 - 粘貼」相同的驗證,而且它感覺不對。我在想,也許Spring有一些類型的功能,可以讓我在security-config.xml中設置,也許調用一個類來對每個帶有參數的URL進行驗證,然後將其重定向到「真實」 URL通過測試。我不知道,那是我想問你的。 ¿您對這種方法有什麼看法? ¿也許我太挑剔了,這不是很糟糕? ¿你知道一個「更好」的方法來做到這一點嗎?

感謝這麼多提前, 海梅

回答

0

我建議在expression-based access control chapter Spring Security的參考密切關注。所以,據我瞭解,你不應該自己檢查權限 - 只需使用@PreAuthorize註釋。嘗試訪問ACL模塊,或者如果它不符合您的要求,可能更好地實現自定義PermissionEvaluator

P.S.還有什麼關於這樣的事情:@PreAuthorize("principal.id == #content.createdBy.id")

+0

非常感謝您的幫助,這正是我所尋找的輸入。 – 2012-08-02 20:21:34

+0

很高興爲您效勞。如果它真的有用,請接受我的回答。 – 2012-08-03 06:25:56