You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@Documented@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface Auth {
}
AuthInterceptor class - Interceptor
@Slf4j@ComponentpublicclassAuthInterceptorimplementsHandlerInterceptor {
@OverridepublicbooleanpreHandle(HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler) throwsException {
Stringurl=request.getRequestURI();
log.info("request url : {}",url);
booleanhasAnnotation = checkAnnotation(handler, Auth.class);
log.info("has annotation : {}",hasAnnotation);
returntrue; //false로 면 Interceptor 통과하지 못해서 Controller까지 들어갈 수 없다.
}
publicbooleancheckAnnotation(Objecthandler,Classclazz){
//resource 에 대한 요청 : javascript, html etc..if(handlerinstanceofResourceHttpRequestHandler){
returntrue;
}
//anntation checkHandlerMethodhandlerMethod=(HandlerMethod) handler;
if(handlerMethod.getMethodAnnotation(clazz)!=null || handlerMethod.getBeanType().getAnnotation(clazz)!=null){
//Auth annotation이 있을 때는 truereturntrue;
}
returnfalse;
}
}
MVCConfig class
inteceptor 등록하기
@Configuration@RequiredArgsConstructorpublicclassMVCConfigimplementsWebMvcConfigurer {
//@Autowired : 순환 참조의 위험이 있기 때문에 생성자로 받는다.privatefinalAuthInterceptorauthInterceptor;
@OverridepublicvoidaddInterceptors(InterceptorRegistryregistry) {
registry.addInterceptor(authInterceptor);
}
}
요청 : http://localhost:8080/api/private/hello
Console 결과
2021-09-29 00:35:08.193 INFO 15748 --- [nio-8080-exec-1] c.e.i.interceptor.AuthInterceptor : request url : /api/private/hello
2021-09-29 00:35:08.196 INFO 15748 --- [nio-8080-exec-1] c.e.i.interceptor.AuthInterceptor : has annotation : true
2021-09-29 00:35:08.203 INFO 15748 --- [nio-8080-exec-1] c.e.i.controller.PrivateController : log private hello
요청 : http://localhost:8080/api/public/hello
Console 결과
2021-09-29 00:35:21.513 INFO 15748 --- [nio-8080-exec-2] c.e.i.interceptor.AuthInterceptor : request url : /api/public/hello
2021-09-29 00:35:21.513 INFO 15748 --- [nio-8080-exec-2] c.e.i.interceptor.AuthInterceptor : has annotation : false
권한 체크 코드 추가하기
나의 서버는 모두 public으로 동작한다.
단, Auth 권한을 가진 요청에 대해서는 세션, 쿠키, RequestParam 등을 확인하는 정책을 사용하겠다.