ACEGI 보안 : 익명 사용자에 대한 인증에 다른 보조 승인을 추가하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/283870

문제

사용자에게 특별 URL에 액세스 키를 제공합니다. 이 특수 URL을 통해 공개 페이지에 액세스하는 사용자는 간단한 익명 사용자와 비교하여 추가 데이터를 볼 수 있어야합니다.

요청에 제공된 매개 변수를 기반으로 익명 사용자에게 추가 역할을하고 싶습니다.

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

현재 나는 Spring 's를 구현하고 있습니다 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?
        }
    }
}
도움이 되었습니까?

해결책

왜 원본을 위임하는 래퍼 클래스를 만들지 말고 몇 가지 추가로 유명한 사람을 추가하는 것이 무엇입니까?

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 );

인증은 이제 추가 역할로 버전으로 대체됩니다. NB 인증이 아직 인증되지 않은 경우를 처리해야 할 수도 있으므로 getAuthorities ()가 NULL을 반환합니다. (래퍼 구현은 현재 래핑 된 인증에서 항상 널이 아닌 배열을 얻을 것이라고 가정합니다).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top