2008-11-12 43 views
4

我給用戶提供了具有訪問密鑰的特殊URL。通過這個特殊的URL訪問公共頁面的用戶應該能夠看到一些額外的數據,而不是簡單的匿名用戶。Acegi安全:我如何添加另一個授權給匿名用戶的身份驗證

我想給基於請求中提供的參數匿名用戶一些額外的角色,所以我可以在我的模板做這樣的事情:

<@sec.authorize ifAnyGranted="ROLE_ADMIN, ROLE_USER, ROLE_INVITED_VISITOR"> 
...some additional stuff for invited user to see 
</@sec.authorize> 
目前

我執行Spring的OncePerRequestfilter

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { 
    if (null != request.getParameter("accessKey")) { 
     if(isValid(request.getParameter("accessKey"))) { 
      Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
      //how do i add additional roles to authenticated (potentially anonymous) user? 
     } 
    } 
} 

回答

6

爲什麼不創建一個包裝類委託給原來的,但一對夫婦額外GrantedAuthorities的補充道:

public class AuthenticationWrapper implements Authentication 
{ 
    private Authentication original; 
    private GrantedAuthority[] extraRoles; 

    public AuthenticationWrapper(Authentication original, GrantedAuthority[] extraRoles) 
    { 
     this.original = original; 
     this.extraRoles = extraRoles; 
    } 

    public GrantedAuthority[] getAuthorities() 
    { 
     GrantedAuthority[] originalRoles = original.getAuthorities(); 
     GrantedAuthority[] roles = new GrantedAuthority[originalRoles.length + extraRoles.length]; 
     System.arraycopy(originalRoles, 0, roles, 0, originalRoles.length); 
     System.arraycopy(extraRoles, 0, roles, originalRoles.length, extraRoles.length); 
     return roles; 
    } 

    public String getName() { return original.getName(); } 
    public Object getCredentials() { return original.getCredentials(); } 
    public Object getDetails() { return original.getDetails(); } 
    public Object getPrincipal() { return original.getPrincipal(); } 
    public boolean isAuthenticated() { return original.isAuthenticated(); } 
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException 
    { 
     original.setAuthenticated(isAuthenticated); 
    } 
} 

,然後做你的過濾器:

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
GrantedAuthority extraRoles = new GrantedAuthority[2]; 
extraRoles[0] = new GrantedAuthorityImpl("Role X"); 
extraRoles[1] = new GrantedAuthorityImpl("Role Y"); 
AuthenticationWrapper wrapper = new AuthenticationWrapper(auth, extraRoles); 
SecurityContextHolder.getContext().setAuthentication(wrapper); 

身份驗證現在由您的版本,具有額外的角色替換。注意您可能需要處理身份驗證尚未通過身份驗證的情況,因此其getAuthorities()返回null。 (包裝器實現當前假定它將始終從其包裝的認證中獲得一個非空數組)

+0

不錯的一個!我自己用附加角色創建了一個新的AnonymousAuthenticationToken來解決這個問題,但這更加優雅。謝謝 – miceuz 2008-11-12 15:45:19