diff --git a/src/main/kotlin/io/csbroker/apiserver/common/util/CookieUtil.kt b/src/main/kotlin/io/csbroker/apiserver/common/util/CookieUtil.kt index e68c5d4a..5331a3f2 100644 --- a/src/main/kotlin/io/csbroker/apiserver/common/util/CookieUtil.kt +++ b/src/main/kotlin/io/csbroker/apiserver/common/util/CookieUtil.kt @@ -39,27 +39,22 @@ fun OAuth2AuthorizationRequest.serialize(): String { .encodeToString(this.toByteArray()) } -fun deserialize(cookie: Cookie): T { - return Base64.getUrlDecoder().decode(cookie.value).fromByteArray() -} - -@Suppress("UNCHECKED_CAST") -private fun ByteArray.fromByteArray(): T { - val byteArrayInputStream = ByteArrayInputStream(this) - val objectInput = ObjectInputStream(byteArrayInputStream) - val result = objectInput.readObject() as T - objectInput.close() - byteArrayInputStream.close() - return result +inline fun Cookie.deserialize(): T { + return Base64.getUrlDecoder().decode(this.value).let { + ByteArrayInputStream(it).use { byteArrayInputStream -> + ObjectInputStream(byteArrayInputStream).use { objectInput -> + objectInput.readObject() + } + } + } as? T ?: throw ClassCastException() } private fun Serializable.toByteArray(): ByteArray { - val byteArrayOutputStream = ByteArrayOutputStream() - val objectOutputStream = ObjectOutputStream(byteArrayOutputStream) - objectOutputStream.writeObject(this) - objectOutputStream.flush() - val result = byteArrayOutputStream.toByteArray() - byteArrayOutputStream.close() - objectOutputStream.close() - return result + return ByteArrayOutputStream().use { + ObjectOutputStream(it).use { objectOutputStream -> + objectOutputStream.writeObject(this) + objectOutputStream.flush() + it.toByteArray() + } + } } diff --git a/src/main/kotlin/io/csbroker/apiserver/repository/common/OAuth2AuthorizationRequestBasedOnCookieRepository.kt b/src/main/kotlin/io/csbroker/apiserver/repository/common/OAuth2AuthorizationRequestBasedOnCookieRepository.kt index ee557823..1ecad5b8 100644 --- a/src/main/kotlin/io/csbroker/apiserver/repository/common/OAuth2AuthorizationRequestBasedOnCookieRepository.kt +++ b/src/main/kotlin/io/csbroker/apiserver/repository/common/OAuth2AuthorizationRequestBasedOnCookieRepository.kt @@ -18,7 +18,7 @@ private const val COOKIE_EXPIRE_SECONDS = 180L class OAuth2AuthorizationRequestBasedOnCookieRepository : AuthorizationRequestRepository { override fun loadAuthorizationRequest(request: HttpServletRequest): OAuth2AuthorizationRequest? { val cookie = getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME) ?: return null - return deserialize(cookie) + return cookie.deserialize() } override fun saveAuthorizationRequest(