feat: 로그인 된 회원 전용 API에 사용할 새로운 Interceptor 및 어노테이션 추가

This commit is contained in:
이상진 2025-09-11 16:58:29 +09:00
parent e02086680b
commit c79a4bdd1f
2 changed files with 54 additions and 0 deletions

View File

@ -19,3 +19,7 @@ annotation class MemberId
annotation class AdminOnly( annotation class AdminOnly(
val privilege: Privilege val privilege: Privilege
) )
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class UserOnly

View File

@ -0,0 +1,50 @@
package roomescape.auth.web.support.interceptors
import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.MDC
import org.springframework.stereotype.Component
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import roomescape.auth.business.CLAIM_TYPE_KEY
import roomescape.auth.exception.AuthErrorCode
import roomescape.auth.exception.AuthException
import roomescape.auth.infrastructure.jwt.JwtUtils
import roomescape.auth.web.support.MDC_MEMBER_ID_KEY
import roomescape.auth.web.support.UserOnly
import roomescape.auth.web.support.accessToken
import roomescape.common.dto.PrincipalType
private val log: KLogger = KotlinLogging.logger {}
@Component
class UserInterceptor(
private val jwtUtils: JwtUtils
) : HandlerInterceptor {
override fun preHandle(
request: HttpServletRequest,
response: HttpServletResponse,
handler: Any
): Boolean {
if ((handler !is HandlerMethod) || (handler.getMethodAnnotation(UserOnly::class.java) == null)) {
return true
}
val token: String? = request.accessToken()
val userId = jwtUtils.extractSubject(token).also { id -> MDC.put(MDC_MEMBER_ID_KEY, id) }
jwtUtils.extractClaim(token, CLAIM_TYPE_KEY).also {
if (it != PrincipalType.USER.name) {
log.warn { "[UserInterceptor] 관리자의 회원 API 접근: id=${userId}" }
throw AuthException(AuthErrorCode.ACCESS_DENIED)
}
}
log.info { "[AuthInterceptor] 인증 완료. userId=$userId" }
return true
}
}