Hello Everyone I have a token refresh system which...
# ktor
p
Hello Everyone I have a token refresh system which requires me to read the response everytime, and based on that i need to decide if i need to refetch the token or proceed with the request. I have come up with a Plugin something like:-
Copy code
val AuthPlugin = createClientPlugin("AuthPlugin", ::AuthPluginConfig) {
    on(Send) { request ->
        val originalCall = proceed(request)
        
        val code = originalCall.response.bodyAsText().decodeResponseCode()
        
        return@on if (code == TOKEN_EXPIRE) {
            val tokenRefreshRequest = HttpRequestBuilder() //Create Token Refresh request
            val newToken = proceed(tokenRefreshRequest).parseToken()
            request.headers[DR_TOKEN] = newToken
            proceed(request)
        } else {
            originalCall
        }
    }
}
But the problem is , ByteReadChannel can only be read once, once i read the response , further layer fails. Am i going in the right direction or is there any way i can make a copy of ByteReadChannel?
a
Have you tried implementing the
AuthProvider
and use the
Auth
plugin (https://ktor.io/docs/client-auth.html)?
p
I did have a look and from what i saw it will work with 401 status code , But the system i am working with gives 200 , and there is a custom status code which comes alongwith response, using which i need to figure out if i need to reauth or not
a
To double receive the response you can use the
SaveBodyPlugin
which, unfortunately, is only available in the
3.0.0-beta-1
release and
3.0.0
EAP releases.
p
I did check it , i don’t think that will help My requirement is more like If the response has auth failure custom code then call another API to get new token and then again make the original request with the newely received token. It is more like a chain request.
If only i could make a copy of the body and use it for my purpose in above shown plugin which i have created,it would have worked.
a
If the request body isn't big you can save the request body to a byte array before executing the first request and then later use it for both requests.