-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #5 from Tiketeer/feat/DEV-245
[DEV-245] Spring Security 설정(JWT) + WaitingController 내 반응형 로직 작업
- Loading branch information
Showing
12 changed files
with
272 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
9 changes: 9 additions & 0 deletions
9
src/main/kotlin/com/tiketeer/TiketeerWaiting/auth/constant/JwtMetadata.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package com.tiketeer.TiketeerWaiting.auth.constant | ||
|
||
enum class JwtMetadata(private val value: String) { | ||
ACCESS_TOKEN("accessToken"), REFRESH_TOKEN("refreshToken"); | ||
|
||
fun value(): String { | ||
return this.value | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
src/main/kotlin/com/tiketeer/TiketeerWaiting/auth/jwt/AccessTokenService.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package com.tiketeer.TiketeerWaiting.auth.jwt | ||
|
||
import io.jsonwebtoken.Jwts | ||
import io.jsonwebtoken.io.Decoders | ||
import io.jsonwebtoken.security.Keys | ||
import org.springframework.beans.factory.annotation.Value | ||
import org.springframework.stereotype.Service | ||
import reactor.core.publisher.Mono | ||
import javax.crypto.SecretKey | ||
|
||
@Service | ||
class AccessTokenService(@Value("\${jwt.secret-key}") secretKey: String) { | ||
private val secretKey: SecretKey = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey)) | ||
|
||
fun verifyToken(accessToken: String): Mono<AccessTokenPayload> { | ||
return Mono.just(accessToken) | ||
.map {token -> Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).payload} | ||
.map {payload -> AccessTokenPayload(payload.subject, payload.get("role", String::class.java))} | ||
} | ||
|
||
data class AccessTokenPayload(val email: String, val role: String) | ||
} |
14 changes: 14 additions & 0 deletions
14
src/main/kotlin/com/tiketeer/TiketeerWaiting/auth/jwt/JwtAuthenticationManager.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package com.tiketeer.TiketeerWaiting.auth.jwt | ||
|
||
import org.springframework.security.authentication.ReactiveAuthenticationManager | ||
import org.springframework.security.core.Authentication | ||
import org.springframework.stereotype.Component | ||
import reactor.core.publisher.Mono | ||
|
||
@Component | ||
class JwtAuthenticationManager: ReactiveAuthenticationManager { | ||
override fun authenticate(authentication: Authentication?): Mono<Authentication> { | ||
return Mono.justOrEmpty(authentication) | ||
.filter { auth -> auth.principal is String && auth.principal != "" } | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
src/main/kotlin/com/tiketeer/TiketeerWaiting/auth/jwt/JwtServerAuthenticationConverter.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.tiketeer.TiketeerWaiting.auth.jwt | ||
|
||
import com.tiketeer.TiketeerWaiting.auth.constant.JwtMetadata | ||
import org.springframework.http.HttpCookie | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken | ||
import org.springframework.security.core.Authentication | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority | ||
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter | ||
import org.springframework.stereotype.Component | ||
import org.springframework.web.server.ServerWebExchange | ||
import reactor.core.publisher.Mono | ||
|
||
@Component | ||
class JwtServerAuthenticationConverter( | ||
private val accessTokenService: AccessTokenService | ||
): ServerAuthenticationConverter { | ||
override fun convert(exchange: ServerWebExchange): Mono<Authentication> { | ||
return Mono.justOrEmpty(extractAccessToken(exchange)) | ||
.map { cookie -> cookie.value } | ||
.flatMap(accessTokenService::verifyToken) | ||
.map(this::createAuthentication) | ||
} | ||
|
||
private fun extractAccessToken(exchange: ServerWebExchange): HttpCookie? { | ||
return exchange.request.cookies.getFirst(JwtMetadata.ACCESS_TOKEN.value()) | ||
} | ||
|
||
private fun createAuthentication(payload: AccessTokenService.AccessTokenPayload): Authentication { | ||
return UsernamePasswordAuthenticationToken( | ||
payload.email, | ||
null, | ||
listOf(SimpleGrantedAuthority(payload.role)) | ||
) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
src/main/kotlin/com/tiketeer/TiketeerWaiting/configuration/SecurityConfig.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
package com.tiketeer.TiketeerWaiting.configuration; | ||
|
||
import com.tiketeer.TiketeerWaiting.auth.jwt.JwtAuthenticationManager | ||
import com.tiketeer.TiketeerWaiting.auth.jwt.JwtServerAuthenticationConverter | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity | ||
import org.springframework.security.config.web.server.SecurityWebFiltersOrder | ||
import org.springframework.security.config.web.server.ServerHttpSecurity | ||
import org.springframework.security.config.web.server.ServerHttpSecurity.CsrfSpec | ||
import org.springframework.security.config.web.server.ServerHttpSecurity.FormLoginSpec | ||
import org.springframework.security.config.web.server.ServerHttpSecurity.HttpBasicSpec | ||
import org.springframework.security.web.server.SecurityWebFilterChain; | ||
import org.springframework.security.web.server.authentication.AuthenticationWebFilter | ||
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository | ||
|
||
@Configuration | ||
@EnableWebFluxSecurity | ||
class SecurityConfig { | ||
@Bean | ||
fun securityWebFilterChain( | ||
http: ServerHttpSecurity, | ||
authenticationManager: JwtAuthenticationManager, | ||
serverAuthenticationConverter: JwtServerAuthenticationConverter | ||
): SecurityWebFilterChain { | ||
val authenticationWebFilter = AuthenticationWebFilter(authenticationManager) | ||
authenticationWebFilter.setServerAuthenticationConverter(serverAuthenticationConverter) | ||
|
||
return http | ||
.csrf(CsrfSpec::disable) | ||
.formLogin(FormLoginSpec::disable) | ||
.httpBasic(HttpBasicSpec::disable) | ||
.securityContextRepository(NoOpServerSecurityContextRepository.getInstance()) | ||
.addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION) | ||
.authorizeExchange { | ||
e -> e.anyExchange().authenticated() | ||
} | ||
.build() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ package com.tiketeer.TiketeerWaiting.domain.waiting.controller | |
import com.tiketeer.TiketeerWaiting.domain.waiting.controller.dto.GetRankAndTokenResponseDto | ||
import com.tiketeer.TiketeerWaiting.domain.waiting.usecase.GetRankAndToken | ||
import com.tiketeer.TiketeerWaiting.domain.waiting.usecase.dto.GetRankAndTokenCommandDto | ||
import org.springframework.security.core.Authentication | ||
import org.springframework.web.bind.annotation.GetMapping | ||
import org.springframework.web.bind.annotation.RequestMapping | ||
import org.springframework.web.bind.annotation.RequestParam | ||
|
@@ -16,10 +17,14 @@ class WaitingController( | |
private val getRankAndTokenUseCase: GetRankAndToken | ||
) { | ||
@GetMapping | ||
fun getRankAndToken(@RequestParam(required = true) ticketingId: UUID): Mono<GetRankAndTokenResponseDto> { | ||
// TODO: JWT 디코딩 필터 적용 후 JWT 내에서 가져오도록 수정 | ||
val email = "[email protected]" | ||
val result = getRankAndTokenUseCase.getRankAndToken(GetRankAndTokenCommandDto(email, ticketingId, System.currentTimeMillis())) | ||
return GetRankAndTokenResponseDto.convertFromDto(result) | ||
fun getRankAndToken( | ||
authentication: Mono<Authentication>, | ||
@RequestParam(required = true) ticketingId: UUID | ||
): Mono<GetRankAndTokenResponseDto> { | ||
return authentication | ||
.map { auth -> auth.name } | ||
.map { email -> GetRankAndTokenCommandDto(email, ticketingId, System.currentTimeMillis()) } | ||
.flatMap(getRankAndTokenUseCase::getRankAndToken) | ||
.map(GetRankAndTokenResponseDto::convertFromDto) | ||
} | ||
} |
7 changes: 2 additions & 5 deletions
7
.../com/tiketeer/TiketeerWaiting/domain/waiting/controller/dto/GetRankAndTokenResponseDto.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,14 @@ | ||
package com.tiketeer.TiketeerWaiting.domain.waiting.controller.dto | ||
|
||
import com.tiketeer.TiketeerWaiting.domain.waiting.usecase.dto.GetRankAndTokenResultDto | ||
import reactor.core.publisher.Mono | ||
|
||
data class GetRankAndTokenResponseDto( | ||
val rank: Long, | ||
val token: String? = null, | ||
) { | ||
companion object { | ||
fun convertFromDto(dto: Mono<GetRankAndTokenResultDto>): Mono<GetRankAndTokenResponseDto> { | ||
return dto.flatMap { r -> | ||
Mono.just(GetRankAndTokenResponseDto(r.rank, r.token)) | ||
} | ||
fun convertFromDto(dto: GetRankAndTokenResultDto): GetRankAndTokenResponseDto { | ||
return GetRankAndTokenResponseDto(dto.rank, dto.token) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
...st/kotlin/com/tiketeer/TiketeerWaiting/domain/waiting/controller/WaitingControllerTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
package com.tiketeer.TiketeerWaiting.domain.waiting.controller | ||
|
||
import com.tiketeer.TiketeerWaiting.auth.constant.JwtMetadata | ||
import com.tiketeer.TiketeerWaiting.configuration.EmbeddedRedisConfig | ||
import com.tiketeer.TiketeerWaiting.domain.waiting.usecase.GetRankAndTokenUseCase | ||
import com.tiketeer.TiketeerWaiting.domain.waiting.usecase.dto.GetRankAndTokenCommandDto | ||
import io.jsonwebtoken.Jwts | ||
import io.jsonwebtoken.io.Decoders | ||
import io.jsonwebtoken.security.Keys | ||
import org.junit.jupiter.api.BeforeEach | ||
import org.junit.jupiter.api.Test | ||
import org.springframework.beans.factory.annotation.Autowired | ||
import org.springframework.beans.factory.annotation.Value | ||
import org.springframework.boot.test.context.SpringBootTest | ||
import org.springframework.context.annotation.Import | ||
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory | ||
import org.springframework.test.web.reactive.server.WebTestClient | ||
import java.util.Date | ||
import java.util.UUID | ||
|
||
@Import(EmbeddedRedisConfig::class) | ||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) | ||
class WaitingControllerTest { | ||
@Autowired | ||
lateinit var webTestClient: WebTestClient | ||
|
||
@Autowired | ||
lateinit var redisConnectionFactory: ReactiveRedisConnectionFactory | ||
|
||
@Autowired | ||
lateinit var getRankAndTokenUseCase: GetRankAndTokenUseCase | ||
|
||
@Value("\${jwt.secret-key}") | ||
lateinit var jwtSecretKey: String | ||
|
||
@Value("\${waiting.entry-size}") | ||
lateinit var entrySize: Number | ||
|
||
@BeforeEach | ||
fun init() { | ||
val flushDb = redisConnectionFactory.reactiveConnection.serverCommands().flushDb() | ||
flushDb.block() | ||
} | ||
|
||
@Test | ||
fun `토큰이 없는 유저 - waiting 요청 - 호출 실패`() { | ||
// given | ||
val ticketingId = UUID.randomUUID() | ||
// when | ||
webTestClient.get().uri("/waiting?ticketingId=$ticketingId") | ||
// then | ||
.exchange() | ||
.expectStatus().isUnauthorized() | ||
} | ||
|
||
@Test | ||
fun `토큰이 있는 유저 - 빈 대기열에 waiting 요청 - 토큰 반환`() { | ||
// given | ||
val email = "[email protected]" | ||
val role = "USER" | ||
val ticketingId = UUID.randomUUID() | ||
|
||
// when | ||
webTestClient.get().uri("/waiting?ticketingId=$ticketingId") | ||
.cookie(JwtMetadata.ACCESS_TOKEN.value(), createAccessToken(email, role, Date())) | ||
// then | ||
.exchange() | ||
.expectStatus().isOk() | ||
.expectBody() | ||
.jsonPath("rank").isEqualTo(0L) | ||
.jsonPath("token").isEqualTo(createPurchaseToken(email, ticketingId)) | ||
} | ||
|
||
@Test | ||
fun `토큰이 있는 유저 - 가득찬 대기열에 waiting 요청 - 토큰 반환 X`() { | ||
// given | ||
val ticketingId = UUID.randomUUID() | ||
for (i in 1..entrySize.toInt()) { | ||
val email = "test${i}@test.com" | ||
val entryTime = System.currentTimeMillis() | ||
val result = getRankAndTokenUseCase.getRankAndToken(GetRankAndTokenCommandDto(email, ticketingId, entryTime)) | ||
result.block() | ||
} | ||
val email = "[email protected]" | ||
val role = "USER" | ||
|
||
// when | ||
webTestClient.get().uri("/waiting?ticketingId=$ticketingId") | ||
.cookie(JwtMetadata.ACCESS_TOKEN.value(), createAccessToken(email, role, Date())) | ||
// then | ||
.exchange() | ||
.expectStatus().isOk() | ||
.expectBody() | ||
.jsonPath("rank").isEqualTo(entrySize.toLong()) | ||
.jsonPath("token").isEmpty() | ||
} | ||
|
||
private fun createPurchaseToken(email: String, ticketingId: UUID): String { | ||
return "$email:$ticketingId" | ||
} | ||
|
||
private fun createAccessToken(email: String, role: String, issuedAt: Date): String { | ||
return Jwts.builder() | ||
.subject(email) | ||
.claim("role", role) | ||
.issuer("tester") | ||
.issuedAt(issuedAt) | ||
.expiration(Date(issuedAt.time + 3 * 60 * 1000)) | ||
.signWith(Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecretKey))) | ||
.compact(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters