2015-11-13 96 views

回答

0

是的,你可以。

爲此,您可以爲每個用戶分配一個特定角色。例如,您的情況下,將擁有該項目的用戶分配爲角色列ADMIN以及所有其他匿名或用戶,然後選擇。安全性可以使請求對具有ANONYMOUS或USER角色的用戶失敗,但只允許具有ADMIN角色的用戶查看項目。

現在,這可以通過Spring Security的以多種方式來實現:

1.使用@PreAuthorize標籤爲各個控制器的方法和測試角色ADMIN/USER/.. 但是,我想,你不希望大幅修改控制器。

  • 短手動方式,這一點,以創建認證對象進入上下文保持器,並使用彈簧引導安全性配置,如低於,例如:

    @Order(1) 
    public class UserFilter extends Filter { 
    
    @Autowired 
    UserService userService; 
    ... 
    
    UserObject userObject = userService.getUser(arg..); 
    List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>(); 
    grantedAuthorityList.add(new SimpleGrantedAuthority((userObject.getRoleName()));//Either ROLE_ADMIN or ROLE_USER 
    Authentication authentication = new PreAuthenticatedAuthenticationToken(userObject.getId(), new Object(), grantedAuthorityList); 
    SecurityContextHolder.getContext().setAuthentication(authentication); 
    chain.doFilter(request,response); 
    
    ... 
    
    } 
    
  • 而安全配置類:

    @Configuration 
        @EnableWebSecurity 
        public class SecurityConfigREST extends WebSecurityConfigurerAdapter { 
    
    
        SecurityConfigREST(){ 
        super(true); 
        } 
        @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
        PreAuthenticatedAuthenticationProvider pap=new PreAuthenticatedAuthenticationProvider(); 
        pap.setPreAuthenticatedUserDetailsService(new PreAuthenticatedGrantedAuthoritiesUserDetailsService()); 
        auth.authenticationProvider(pap); 
    } 
    @Override 
        protected void configure(HttpSecurity http) throws Exception { 
        http 
         .authorizeRequests() 
         .regexMatchers("^/items.*$").hasAuthority("ROLE_ADMIN") //The role which should have access to /items/1,2.. URL 
         .anyRequest().authenticated(); 
        } 
        } 
    
  • 使用的UserDetailsS​​ervice在安全配置上述和負載噸他的用戶及其在預驗證身份驗證提供程序中的角色。 參見:http://docs.spring.io/autorepo/docs/spring-security/3.2.2.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetailsService.html
  • 說了這麼多,它也是一個不錯的設計,不通過的項目(1,2,3)通過URL號碼,如可能導致潛在的問題後,所以使用GET和通過JSON請求身體,因爲它這樣的:

    /items RequestMethod.GET 
    
    { 
    "itemList" : [1,2,3,4,5] 
    } 
    
    Hope that helps. 
    
    +0

    問題是如何限制結果只有屬於用戶的實體。角色沒有任何幫助。我不在乎用戶是管理員還是凡人,他不應該被允許看到屬於他自己的實體。 –

    +0

    呵呵?它總是很好地將角色附加到你的項目列表或resources.Its一個很好的做法。如果不需要,那麼你可以基於來自JPA倉庫的密鑰迭代:repository.findByUserId(Long userId),它只是簡單的彈簧數據jpa,(沒有彈簧安全性,因此與問題衝突)。此外,在上述聲明中,你自相矛盾,「他不應該被允許看到屬於他自己的實體」..請更正它..謝謝。 –

    +1

    是的,應該是「那*不*屬於他自己」,但它看起來像SO不允許在一段時間後編輯評論。是的,角色很好,我確實使用它們。但這與問題的情況無關。問題在於spring-data-rest使所有存儲庫在映射'/ {repository}'下可用,允許訪問所有實體。所以問題是如何只返回屬於用戶的實體。 –

    相關問題