스프링 시큐리티/실전프로젝트 - 인가 프로세스 DB 연동 웹 계층 구현

ch09. 아이피 접속 제한하기 - CustomIpAddressVoter

webmaster 2022. 1. 25. 11:42
728x90

동작 과정

  • AccessDecusionManager 가 여러 Voter를 가지고 있다.
  • 심의 기준
    • 특정한 IP 만 접근이 가능하도록 심의하는 Voter 추가
    • Voter 중에서 가장 먼저 심사하도록 하여 허용된 IP 일 경우에만 최종 승인 및 거부 결정을 하도록 한다
    • 허용된 IP 이면 ACCESS_GRANTED 가 아닌 ACCESS_ABSTAIN을리턴해서 추가 심의를 계속 진행하도록 한다
    • 허용된 IP 가 아니면 ACCESS_DENIED를 리턴하지 않고 즉시 예외 발생하여 최종 자원 접근 거부
  • IP Entity 추가
    • IP Entity
  • AccessIpRepository 생성
    • Repository
  • voterManager의 accessDecisionVoter를 추가한다.
    • IP인증처리가 먼저 동작해야하므로 위에 쓴다(순차적 실행)
  • IPAddressVoter
    • public class IpAddressVoter implements AccessDecisionVoter<Object> {
      
          private SecurityResourceService securityResourceService;
      
          public IpAddressVoter(SecurityResourceService securityResourceService) {
              this.securityResourceService = securityResourceService;
          }
      
          @Override
          public boolean supports(ConfigAttribute attribute) {
              return true;
          }
      
          @Override
          public boolean supports(Class<?> clazz) {
              return true;
          }
      
          @Override
          public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
              //인증정보, Location, 권한정보
      
              WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();//사용자의 IP주소를 얻을수 있다.
              String remoteAddress = details.getRemoteAddress();// IP 주소
      
              List<String> accessIpList = securityResourceService.getAccessIpList();
              int result = ACCESS_DENIED; //기본값
              for (String ipAddress : accessIpList){
                  if(remoteAddress.equals(ipAddress))
                      return ACCESS_ABSTAIN; //다른 심의를 하기 위해 GRANT가 아닌 ABSTAIN 리턴
              }
              if(result == ACCESS_DENIED){
                  throw new AccessDeniedException("Invalid IpAddress");
                  //예외를 발생시켜 더이상 인증 안되게 한다.
              }
              return result;
          }
      }
    • 인증 성공 => return ACCESS_ABSTAIN (다른 인증도 해야 되기 때문)
    • 인증 실패 => 예외 발생 (예외를 발생시켜 곧바로 인증에 실패하도록 한다)
728x90