-
Notifications
You must be signed in to change notification settings - Fork 0
Implement Kakao OAuth login using OIDC ID token #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
a2050cd
configure application profiles and secrets management
subsub97 21dd3f8
add Member Entity and Associate existing entities with Member
subsub97 dcd3830
Implement JWT authentication feature
subsub97 715ea36
Implement OIDC client for Kakao login
subsub97 3d79b52
Refactor separate auth infrastructure from business logic
subsub97 972d026
edit submodules import path
subsub97 3f91c9e
Rename test config to inherit main application settings
subsub97 4eada87
Set default spring profile to 'local'
subsub97 6a99723
Fix CI test failure by adding submodule checkout token
subsub97 00ac5fb
Refactor configuration files to use secret properties for sensitive data
subsub97 dd43b08
Merge remote-tracking branch 'origin/kakao-login' into kakao-login
subsub97 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,3 @@ | ||
| [submodule "src/main/resources/moa-secret"] | ||
| path = src/main/resources/moa-secret | ||
| url = https://github.com/subsub97/moa-secret |
This file contains hidden or 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
Empty file.
This file contains hidden or 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
This file contains hidden or 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,5 @@ | ||
| package com.moa.common.auth | ||
|
|
||
| object AuthConstants { | ||
| const val CURRENT_MEMBER_ID = "currentMemberId" | ||
| } |
This file contains hidden or 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.moa.common.auth | ||
|
|
||
| @Target(AnnotationTarget.VALUE_PARAMETER) | ||
| @Retention(AnnotationRetention.RUNTIME) | ||
| annotation class AuthenticatedMember | ||
|
|
||
| data class AuthenticatedMemberInfo( | ||
| val id: Long, | ||
| ) |
34 changes: 34 additions & 0 deletions
34
src/main/kotlin/com/moa/common/auth/AuthenticatedMemberResolver.kt
This file contains hidden or 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,34 @@ | ||
| package com.moa.common.auth | ||
|
|
||
| import com.moa.common.exception.BadRequestException | ||
| import com.moa.common.exception.ErrorCode | ||
| import org.springframework.core.MethodParameter | ||
| import org.springframework.stereotype.Component | ||
| import org.springframework.web.bind.support.WebDataBinderFactory | ||
| import org.springframework.web.context.request.NativeWebRequest | ||
| import org.springframework.web.context.request.RequestAttributes | ||
| import org.springframework.web.method.support.HandlerMethodArgumentResolver | ||
| import org.springframework.web.method.support.ModelAndViewContainer | ||
|
|
||
| @Component | ||
| class AuthenticatedMemberResolver : HandlerMethodArgumentResolver { | ||
|
|
||
| override fun supportsParameter(parameter: MethodParameter): Boolean { | ||
| return parameter.hasParameterAnnotation(AuthenticatedMember::class.java) && | ||
| parameter.parameterType == AuthenticatedMemberInfo::class.java | ||
| } | ||
|
|
||
| override fun resolveArgument( | ||
| parameter: MethodParameter, | ||
| mavContainer: ModelAndViewContainer?, | ||
| webRequest: NativeWebRequest, | ||
| binderFactory: WebDataBinderFactory?, | ||
| ): AuthenticatedMemberInfo { | ||
| val memberId = webRequest.getAttribute( | ||
| AuthConstants.CURRENT_MEMBER_ID, | ||
| RequestAttributes.SCOPE_REQUEST | ||
| ) as? Long ?: throw BadRequestException(ErrorCode.INVALID_ID_TOKEN) | ||
|
|
||
| return AuthenticatedMemberInfo(id = memberId) | ||
| } | ||
| } | ||
This file contains hidden or 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,69 @@ | ||
| package com.moa.common.auth | ||
|
|
||
| import io.jsonwebtoken.Claims | ||
| import io.jsonwebtoken.Jwts | ||
| import io.jsonwebtoken.security.Keys | ||
| import jakarta.servlet.http.HttpServletRequest | ||
| import org.springframework.beans.factory.annotation.Value | ||
| import org.springframework.stereotype.Component | ||
| import java.nio.charset.StandardCharsets | ||
| import java.time.Duration | ||
| import java.time.LocalDateTime | ||
| import java.time.ZoneId | ||
| import java.util.* | ||
|
|
||
| @Component | ||
| class JwtTokenProvider( | ||
| @Value("\${jwt.secret-key}") | ||
| private val accessTokenSecretKey: String, | ||
|
|
||
| @Value("\${jwt.expiration-milliseconds}") | ||
| private val accessTokenExpirationInMilliseconds: Long, | ||
| ) { | ||
|
|
||
| private val accessKey = Keys.hmacShaKeyFor(accessTokenSecretKey.toByteArray(StandardCharsets.UTF_8)) | ||
|
|
||
| fun createAccessToken(userId: Long): String { | ||
| val now = LocalDateTime.now() | ||
| val expiryDate = now.plus(Duration.ofMillis(accessTokenExpirationInMilliseconds)) | ||
|
|
||
| return Jwts.builder() | ||
| .subject(userId.toString()) | ||
| .issuedAt(toDate(now)) | ||
| .expiration(toDate(expiryDate)) | ||
| .signWith(accessKey) | ||
| .compact() | ||
| } | ||
|
|
||
| fun extractToken(request: HttpServletRequest): String? { | ||
| val bearerToken = request.getHeader("Authorization") | ||
| return if (bearerToken != null && bearerToken.startsWith("Bearer ")) { | ||
| bearerToken.substring(7) | ||
| } else null | ||
| } | ||
|
|
||
| fun getUserIdFromToken(token: String): Long? { | ||
| return getClaims(token).subject.toLong() | ||
| } | ||
|
|
||
| fun validateToken(token: String): Boolean { | ||
| return try { | ||
| getClaims(token) | ||
| true | ||
| } catch (ex: Exception) { | ||
| false | ||
| } | ||
| } | ||
|
|
||
| private fun getClaims(token: String): Claims { | ||
| return Jwts.parser() | ||
| .verifyWith(accessKey) | ||
| .build() | ||
| .parseSignedClaims(token) | ||
| .payload | ||
| } | ||
| } | ||
|
|
||
| fun toDate(localDateTime: LocalDateTime): Date { | ||
| return Date.from(localDateTime.atZone(ZoneId.of("Asia/Seoul")).toInstant()) | ||
| } |
This file contains hidden or 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,16 @@ | ||
| package com.moa.common.config | ||
|
|
||
| import com.moa.common.auth.AuthenticatedMemberResolver | ||
| import org.springframework.context.annotation.Configuration | ||
| import org.springframework.web.method.support.HandlerMethodArgumentResolver | ||
| import org.springframework.web.servlet.config.annotation.WebMvcConfigurer | ||
|
|
||
| @Configuration | ||
| class WebConfig( | ||
| private val authenticatedMemberResolver: AuthenticatedMemberResolver, | ||
| ) : WebMvcConfigurer { | ||
|
|
||
| override fun addArgumentResolvers(resolvers: MutableList<HandlerMethodArgumentResolver>) { | ||
| resolvers.add(authenticatedMemberResolver) | ||
| } | ||
| } |
This file contains hidden or 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
This file contains hidden or 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
68 changes: 68 additions & 0 deletions
68
src/main/kotlin/com/moa/common/filter/JwtAuthenticationFilter.kt
This file contains hidden or 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,68 @@ | ||
| package com.moa.common.filter | ||
|
|
||
| import com.moa.common.auth.AuthConstants | ||
| import com.moa.common.auth.JwtTokenProvider | ||
| import com.moa.common.exception.ErrorCode | ||
| import jakarta.servlet.FilterChain | ||
| import jakarta.servlet.http.HttpServletRequest | ||
| import jakarta.servlet.http.HttpServletResponse | ||
| import org.springframework.http.MediaType | ||
| import org.springframework.stereotype.Component | ||
| import org.springframework.web.filter.OncePerRequestFilter | ||
| import tools.jackson.databind.ObjectMapper | ||
|
|
||
| @Component | ||
| class JwtAuthenticationFilter( | ||
| private val jwtTokenProvider: JwtTokenProvider, | ||
| private val objectMapper: ObjectMapper, | ||
| ) : OncePerRequestFilter() { | ||
|
|
||
| companion object { | ||
| private val EXCLUDED_PATHS = listOf( | ||
| "/api/v1/auth", | ||
| "/h2-console", | ||
| ) | ||
| } | ||
|
|
||
| override fun shouldNotFilter(request: HttpServletRequest): Boolean { | ||
| val path = request.requestURI | ||
| return EXCLUDED_PATHS.any { path.startsWith(it) } | ||
| } | ||
|
|
||
| override fun doFilterInternal( | ||
| request: HttpServletRequest, | ||
| response: HttpServletResponse, | ||
| filterChain: FilterChain, | ||
| ) { | ||
| val token = jwtTokenProvider.extractToken(request) | ||
|
|
||
| if (token == null || !jwtTokenProvider.validateToken(token)) { | ||
| writeUnauthorizedResponse(response) | ||
| return | ||
| } | ||
|
|
||
| val memberId = jwtTokenProvider.getUserIdFromToken(token) | ||
| if (memberId == null) { | ||
| writeUnauthorizedResponse(response) | ||
| return | ||
| } | ||
|
|
||
| request.setAttribute(AuthConstants.CURRENT_MEMBER_ID, memberId) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 오오오 이렇게 했구나~~ 구우웃! |
||
| filterChain.doFilter(request, response) | ||
| } | ||
|
|
||
| private fun writeUnauthorizedResponse(response: HttpServletResponse) { | ||
| response.status = HttpServletResponse.SC_UNAUTHORIZED | ||
| response.contentType = MediaType.APPLICATION_JSON_VALUE | ||
| response.characterEncoding = "UTF-8" | ||
|
|
||
| val errorCode = ErrorCode.UNAUTHORIZED | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이 부분 jackson 쓰면 깔끔해질텐데~! 🙋 |
||
| val errorResponse = mapOf( | ||
| "code" to errorCode.code, | ||
| "message" to errorCode.message, | ||
| "content" to null | ||
| ) | ||
|
|
||
| objectMapper.writeValue(response.writer, errorResponse) | ||
| } | ||
| } | ||
This file contains hidden or 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,52 @@ | ||
| package com.moa.common.oidc | ||
|
|
||
| import org.springframework.stereotype.Component | ||
| import org.springframework.web.client.RestClient | ||
| import java.math.BigInteger | ||
| import java.security.KeyFactory | ||
| import java.security.interfaces.RSAPublicKey | ||
| import java.security.spec.RSAPublicKeySpec | ||
| import java.util.* | ||
|
|
||
| @Component | ||
| class OidcClient( | ||
| private val restClient: RestClient = RestClient.create(), | ||
| ) { | ||
| fun fetchPublicKeys(jwksUri: String): Map<String, RSAPublicKey> { | ||
| val response = try { | ||
| restClient.get() | ||
| .uri(jwksUri) | ||
| .retrieve() | ||
| .body(JwksResponse::class.java) | ||
| } catch (ex: Exception) { | ||
| throw RuntimeException("OIDC 공개키를 가져오는데 실패했습니다.", ex) | ||
| } | ||
|
|
||
| return response?.keys | ||
| ?.filter { it.kty == "RSA" && it.use == "sig" } | ||
| ?.associate { key -> | ||
| key.kid to createRsaPublicKey(key.n, key.e) | ||
| } ?: emptyMap() | ||
| } | ||
|
|
||
| private fun createRsaPublicKey(n: String, e: String): RSAPublicKey { | ||
| val decoder = Base64.getUrlDecoder() | ||
| val modulus = BigInteger(1, decoder.decode(n)) | ||
| val exponent = BigInteger(1, decoder.decode(e)) | ||
| val spec = RSAPublicKeySpec(modulus, exponent) | ||
| val keyFactory = KeyFactory.getInstance("RSA") | ||
| return keyFactory.generatePublic(spec) as RSAPublicKey | ||
| } | ||
|
|
||
| private data class JwksResponse( | ||
| val keys: List<JwkKey>, | ||
| ) | ||
|
|
||
| private data class JwkKey( | ||
| val kid: String, | ||
| val kty: String, | ||
| val use: String?, | ||
| val n: String, | ||
| val e: String, | ||
| ) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wow 재밋다잉~