Skip to content

Commit

Permalink
feat: access token 관리 방식을 cookie 로 변경 (#86)
Browse files Browse the repository at this point in the history
* feat: access token 관리 방식을 cookie 로 변경

* refactor: 로그인 요청 Origin으로 리다이렉트

---------

Co-authored-by: TaeyeonRoyce <[email protected]>
  • Loading branch information
shin-mallang and TaeyeonRoyce authored Nov 16, 2024
1 parent c49f2de commit a9a1f02
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.celuveat.auth.adapter.`in`.rest

import com.celuveat.auth.application.port.`in`.ExtractMemberIdUseCase
import com.celuveat.common.adapter.`in`.rest.getAccessTokenFromCookie
import com.celuveat.common.adapter.`in`.rest.getTokenAuthorizationOrNull
import com.celuveat.common.adapter.`in`.rest.toHttpServletRequest
import org.springframework.core.MethodParameter
Expand All @@ -26,7 +27,7 @@ class AuthContextArgumentResolver(
binderFactory: WebDataBinderFactory?,
): Any? {
val httpServletRequest = webRequest.toHttpServletRequest()
return httpServletRequest.getTokenAuthorizationOrNull()
return httpServletRequest.getAccessTokenFromCookie()
?.let { AuthContext(extractMemberIdUseCase.extract(it)) }
?: AuthContext.guest()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ inline fun NativeWebRequest.toHttpServletRequest(
fun HttpServletRequest.getTokenAuthorizationOrNull(): String? {
return this.getHeader("Authorization")?.removePrefix(TOKEN_AUTHORIZATION_SCHEME) ?: return null
}

fun HttpServletRequest.getAccessTokenFromCookie(): String? {
return this.cookies?.firstOrNull { it.name == "accessToken" }?.value
}
21 changes: 21 additions & 0 deletions src/main/kotlin/com/celuveat/common/utils/CookieExtensions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.celuveat.common.utils

import jakarta.servlet.http.Cookie
import jakarta.servlet.http.HttpServletResponse

inline fun HttpServletResponse.addSecureCookie(
name: String,
value: String,
path: String = "/",
maxAge: Int = -1,
isHttpOnly: Boolean = true,
isSecure: Boolean = true
) {
val cookie = Cookie(name, value).apply {
this.isHttpOnly = isHttpOnly
this.secure = isSecure
this.path = path
this.maxAge = maxAge
}
this.addCookie(cookie)
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.enums.ParameterIn
import io.swagger.v3.oas.annotations.security.SecurityRequirement
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpHeaders
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.DeleteMapping
Expand Down Expand Up @@ -41,7 +42,8 @@ interface SocialLoginApi {
example = "http://localhost:3000",
)
@RequestHeader(HttpHeaders.ORIGIN) requestOrigin: String,
): LoginResponse
response: HttpServletResponse,
): ResponseEntity<LoginResponse>

@Operation(summary = "소셜 로그인을 위한 Url 로 redirect")
@GetMapping("/url/{socialLoginType}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ package com.celuveat.member.adapter.`in`.rest
import com.celuveat.auth.adapter.`in`.rest.Auth
import com.celuveat.auth.adapter.`in`.rest.AuthContext
import com.celuveat.auth.application.port.`in`.CreateAccessTokenUseCase
import com.celuveat.common.utils.addSecureCookie
import com.celuveat.member.adapter.`in`.rest.response.LoginResponse
import com.celuveat.member.application.port.`in`.ReadSocialLoginUrlUseCase
import com.celuveat.member.application.port.`in`.SocialLoginUseCase
import com.celuveat.member.application.port.`in`.WithdrawSocialLoginUseCase
import com.celuveat.member.application.port.`in`.command.SocialLoginCommand
import com.celuveat.member.application.port.`in`.command.WithdrawSocialLoginCommand
import com.celuveat.member.domain.SocialLoginType
import jakarta.servlet.http.HttpServletResponse
import java.net.URI
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
Expand All @@ -33,11 +37,18 @@ class SocialLoginController(
@PathVariable socialLoginType: SocialLoginType,
@RequestParam authCode: String,
@RequestHeader(HttpHeaders.ORIGIN) requestOrigin: String,
): LoginResponse {
response: HttpServletResponse,
): ResponseEntity<LoginResponse> {
val command = SocialLoginCommand(socialLoginType, authCode, requestOrigin)
val memberId = socialLoginUseCase.login(command)
val token = createAccessTokenUseCase.create(memberId)
return LoginResponse.from(token)
response.addSecureCookie(
name = "accessToken",
value = token.token,
)
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create(requestOrigin))
.build()
}

@GetMapping("/url/{socialLoginType}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import com.navercorp.fixturemonkey.kotlin.giveMeBuilder
import com.ninjasquad.springmockk.MockkBean
import io.kotest.core.spec.style.FunSpec
import io.mockk.every
import jakarta.servlet.http.Cookie
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.test.web.servlet.MockMvc
Expand Down Expand Up @@ -55,7 +56,7 @@ class CelebrityControllerTest(
every { readInterestedCelebritiesUseCase.getInterestedCelebrities(memberId) } returns results

mockMvc.get("/celebrities/interested") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(results)) }
Expand All @@ -76,7 +77,7 @@ class CelebrityControllerTest(
every { addInterestedCelebrityUseCase.addInterestedCelebrity(command) } returns Unit

mockMvc.post("/celebrities/interested/{celebrityId}", celebrityId) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
}.andDo {
Expand All @@ -96,7 +97,7 @@ class CelebrityControllerTest(
every { deleteInterestedCelebrityUseCase.deleteInterestedCelebrity(command) } returns Unit

mockMvc.delete("/celebrities/interested/{celebrityId}", celebrityId) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
}.andDo {
Expand Down Expand Up @@ -134,7 +135,7 @@ class CelebrityControllerTest(
every { readCelebrityUseCase.readCelebrity(query) } returns result

mockMvc.get("/celebrities/{celebrityId}", celebrityId) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(CelebrityWithInterestedResponse.from(result))) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.just
import io.mockk.unmockkAll
import jakarta.servlet.http.Cookie
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.http.MediaType
Expand Down Expand Up @@ -47,7 +48,7 @@ class MemberControllerTest(
every { extractMemberIdUseCase.extract(accessToken) } returns memberId

mockMvc.get("/members/profile") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(response)) }
Expand Down Expand Up @@ -80,7 +81,7 @@ class MemberControllerTest(
every { extractMemberIdUseCase.extract(accessToken) } returns memberId

mockMvc.patch("/members/profile") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
contentType = MediaType.APPLICATION_JSON
content = mapper.writeValueAsString(request)
}.andExpect {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import io.kotest.core.test.TestResult
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.unmockkAll
import jakarta.servlet.http.Cookie
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.test.web.servlet.MockMvc
Expand Down Expand Up @@ -48,8 +49,9 @@ class SocialLoginControllerTest(
param("authCode", authCode)
header("Origin", requestOrigin)
}.andExpect {
status { isOk() }
jsonPath("$.accessToken") { value("accessToken") }
status { isFound() }
header { string("Location", requestOrigin) }
cookie { exists("accessToken") }
}.andDo {
print()
}
Expand Down Expand Up @@ -108,7 +110,7 @@ class SocialLoginControllerTest(

mockMvc.delete("/social-login/withdraw", socialLoginType) {
header("Origin", requestOrigin)
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isNoContent() }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import io.kotest.core.test.TestResult
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.unmockkAll
import jakarta.servlet.http.Cookie
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.test.web.servlet.MockMvc
Expand Down Expand Up @@ -90,7 +91,7 @@ class RestaurantControllerTest(
every { readInterestedRestaurantsUseCase.readInterestedRestaurant(query) } returns results

mockMvc.get("/restaurants/interested") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
param("page", page.toString())
param("size", "3")
}.andExpect {
Expand All @@ -114,7 +115,7 @@ class RestaurantControllerTest(
every { addInterestedRestaurantsUseCase.addInterestedRestaurant(command) } returns Unit

mockMvc.post("/restaurants/interested/{restaurantId}", restaurantId) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
}.andDo {
Expand All @@ -135,7 +136,7 @@ class RestaurantControllerTest(
every { deleteInterestedRestaurantsUseCase.deleteInterestedRestaurant(command) } returns Unit

mockMvc.delete("/restaurants/interested/{restaurantId}", restaurantId) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
}.andDo {
Expand Down Expand Up @@ -164,7 +165,7 @@ class RestaurantControllerTest(
every { readCelebrityVisitedRestaurantUseCase.readCelebrityVisitedRestaurant(query) } returns results

mockMvc.get("/restaurants/celebrity/$celebrityId") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
param("page", page.toString())
param("size", "3")
}.andExpect {
Expand Down Expand Up @@ -211,7 +212,7 @@ class RestaurantControllerTest(
every { readCelebrityRecommendRestaurantsUseCase.readCelebrityRecommendRestaurants(any()) } returns results

mockMvc.get("/restaurants/celebrity/recommend") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(response)) }
Expand Down Expand Up @@ -268,7 +269,7 @@ class RestaurantControllerTest(

val response = SliceResponse.from(sliceResult, RestaurantPreviewResponse::from)
mockMvc.get("/restaurants") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
param("category", category)
param("region", region)
param("page", page.toString())
Expand Down Expand Up @@ -313,7 +314,7 @@ class RestaurantControllerTest(

val response = SliceResponse.from(sliceResult, RestaurantPreviewResponse::from)
mockMvc.get("/restaurants") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
param("category", category)
param("region", region)
param("lowLongitude", "127.0")
Expand Down Expand Up @@ -356,7 +357,7 @@ class RestaurantControllerTest(

val response = SliceResponse.from(sliceResult, RestaurantPreviewResponse::from)
mockMvc.get("/restaurants/weekly") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
param("page", page.toString())
param("size", size.toString())
}.andExpect {
Expand All @@ -382,7 +383,7 @@ class RestaurantControllerTest(
every { readNearbyRestaurantsUseCase.readNearbyRestaurants(query) } returns results

mockMvc.get("/restaurants/nearby/{restaurantId}", 1L) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(response)) }
Expand All @@ -407,7 +408,7 @@ class RestaurantControllerTest(
every { readRestaurantDetailUseCase.readRestaurantDetail(query) } returns results

mockMvc.get("/restaurants/{restaurantId}", restaurantId) {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(response)) }
Expand All @@ -429,7 +430,7 @@ class RestaurantControllerTest(
every { extractMemberIdUseCase.extract(accessToken) } returns memberId

mockMvc.get("/restaurants/popular") {
header("Authorization", "Bearer $accessToken")
cookie(Cookie("accessToken", "$accessToken"))
}.andExpect {
status { isOk() }
content { json(mapper.writeValueAsString(response)) }
Expand Down

0 comments on commit a9a1f02

Please sign in to comment.