Programming/Java
[SpringBoot] AOP를 활용하여 컨트롤러 메소드 단위 IP 제약
brad.min
2023. 9. 11. 17:41
반응형
특정 URL은 정해진 IP만 접근이 가능하도록 제약을 걸기 위해 AOP를 활용해 보았다.
환경
Srping Boot 2.5.5
anotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IpFilter {
}
어노테이션으로 메소드에 IP 제약을 걸기 위해 IpFilter 파일을 만들었다.
@Target(ElementType.METHOD) : @Target은 어노테이션을 적용할 타입을 지정하는 것이다. 여기서 ElementType.METHOD는 클래스의 메소드에만 해당 어노테이션을 붙일 수 있다고 정의 하는 것이다.
@Retention(RetentionPolicy.RUNTIME) : 프로그램이 실행 중일 때 해당 어노테이션 정보를 사용할 수 있게 한다. 목적에따라 Class, Source 를 지정할 수 있다.
Aspect
@Slf4j
@Component
@Aspect
public class IpFilterAspect {
// 허용할 IP 주소 목록을 설정합니다.
private static final List<String> allowedIpAddresses = new ArrayList<>();
static {
//허용할 IP 주소 추가
allowedIpAddresses.add("127.0.0.1");
}
@Before("@annotation(IpFilter)")
public void checkIpAddress(IpFilter IpFilter) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String clientIpAddress = getClientIpAddress(request);
if (!allowedIpAddresses.contains(clientIpAddress)) {
throw new IpfilterException("IP 주소가 허용되지 않습니다.");
}
}
private String getClientIpAddress(HttpServletRequest request) {
String clientIP = request.getRemoteAddr();
return clientIP;
}
}
@Aspect: AOP 방식을 적용하기 위해 붙이는 어노테이션이다.
@Before("@annotation(IpFilter)"): @Before은 타겟 메소드가 실행되기 전에 checkIpAddress 메소드를 실행하겠다는 의미이다.
RequestContextHolder:currentReqeustAttribute(): 전역에서 Request 객체의 정보를 가져올 때 사용하는 클래스이다. 자세한 설명은 아래의 링크를 통해 확인 할 수 있다.
https://gompangs.tistory.com/entry/Spring-RequestContextHolder
적용
@IpFilter
@GetMapping("/list")
public String test(Model model) throws Exception{
비지니스 로직
return "페이지";
}
@IpFilter 어노테이션을 통해 해당 메소드에 대한 IP 제약을 적용 할 수 있었다.
반응형