Retrofit2: how to save cookies from response - android

I need to add some authorization information from cookie in response to next requests.
It works in postman - I make authorization request, then second request, which works fine. But if I delete cookies - second request returns error and I have to do authorization request again.
But in my application this second request always returns the same error. I tried to find needed cookie by using interceptor, but I hadn't found it
val client = OkHttpClient.Builder()
.addInterceptor(OAuthInterceptor())
private class OAuthInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
val request = chain.request()
com.app.logic.toLog("${chain.proceed(request).header("set-cookie")} ") // it's not that cookie what I looking for
val headers = chain.proceed(request).headers()
headers.names().forEach {
val s = headers.get(it)
com.app.logic.toLog("$it -> $s")
}
return chain + (Session.authConsumer?.let { consumer ->
consumer.sign(request).unwrap() as Request
} ?: request)
}
}
Does anybody know what else could I try?

So, finally I've found solution for working with cookies
val client = OkHttpClient.Builder()
.cookieJar(UvCookieJar())
private class UvCookieJar : CookieJar {
private val cookies = mutableListOf<Cookie>()
override fun saveFromResponse(url: HttpUrl, cookieList: List<Cookie>) {
cookies.clear()
cookies.addAll(cookieList)
}
override fun loadForRequest(url: HttpUrl): List<Cookie> =
cookies
}

You can use this this gist on how to intercept cookies when you receive them and send them back in your request in header.

Related

How to regenerate token in Android GraphQL?

What is the better approach to regenerate the JWT token using refresh token in Apollo Graphql in Andriod Kotlin?.
Now we are using an Auth interceptor that extends ApolloInterceptor to attach the JWT token in the request header.
I want to check whether the Toke expires from here and it should call another mutation to generate a new token. Then it should proceed with the previous call with the new token.
Please refer to the code below
class AuthInterceptor(private val jwtToken: String) : ApolloInterceptor {
override fun interceptAsync(
request: ApolloInterceptor.InterceptorRequest,
chain: ApolloInterceptorChain,
dispatcher: Executor,
callBack: ApolloInterceptor.CallBack
) {
val header = request.requestHeaders.toBuilder().addHeader(
HEADER_AUTHORIZATION,
"$HEADER_AUTHORIZATION_BEARER $jwtToken"
).build()
chain.proceedAsync(request.toBuilder().requestHeaders(header).build(), dispatcher, callBack)
}
override fun dispose() {}
companion object {
private const val HEADER_AUTHORIZATION = "Authorization"
private const val HEADER_AUTHORIZATION_BEARER = "Bearer"
}
}
If you are using Apollo Android Client V3 and Using Kotlin Coroutine then use Apollo Runtime Dependency and Try HttpInterceptor instead of ApolloInterceptor. I think this is the better/best approach. For Reference Click Here
In your app-level build.gradle file
plugins {
......
id("com.apollographql.apollo3").version("3.5.0")
.....
}
dependencies {
implementation("com.apollographql.apollo3:apollo-runtime")
}
Now write your interceptor for the Apollo client.
FYI: If you've added the Authorization header using Interceptor or using addHttpHeader in client already then remove it or don't add header here val response = chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build()), just build the request. Otherwise Authorization header will add multiple times in the request. So, be careful.
class AuthorizationInterceptor #Inject constructor(
val tokenRepo: YourTokenRepo
) : HttpInterceptor {
private val mutex = Mutex()
override suspend fun intercept(request: HttpRequest, chain: HttpInterceptorChain): HttpResponse {
var token = mutex.withLock {
// get current token
}
val response = chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build())
return if (response.statusCode == 401) {
token = mutex.withLock {
// get new token from your refresh token API
}
chain.proceed(request.newBuilder().addHeader("Authorization", "Bearer $token").build())
} else {
response
}
}
}
Configure your Apollo client like below.
ApolloClient.Builder()
.httpServerUrl(BASE_GRAPHQL_URL)
.webSocketServerUrl(BASE_GRAPHQL_WEBSOCKET_ENDPOINT) // if needed
.addHttpHeader("Accept", "application/json")
.addHttpHeader("Content-Type", "application/json")
.addHttpHeader("User-Agent", userAgent)
.addHttpInterceptor(AuthorizationInterceptor(YourTokenRepo))
.httpExposeErrorBody(true)
.build()

Http requests with OkHttp Interceptor doesn't works

I'm using Retrofit with OkHttp Interceptor to work with API.
Interceptor adding cookie header to each request.
Interceptors code:
class AddCookiesInterceptor: Interceptor {
#Inject
lateinit var cookiesDao: CookiesDao
init {
App.getAppComponent().inject(this)
}
#SuppressLint("CheckResult")
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
cookiesDao.getAll()
.subscribeOn(Schedulers.io())
.subscribe { cookies ->
builder.addHeader("Cookie", "JWT=" + cookies.jwt)
}
return chain.proceed(builder.build())
}
}
While debuging i see, that interceptor updates request and adds cookie header with value, but when server reachs the request it returns an error (400 http code auth again).
if i manualy add Header into request like this
#GET("/api.tree/get_element/")
#Headers("Content-type: application/json", "X-requested-with: XMLHttpRequest", "Cookie: jwt_value")
fun getElementId(): Maybe<ResponseBody>
Api returns 200 http code and it works.
Your code is not working because you are adding the header asynchronously, this is a "timeline" of what's happening in your flow:
init builder -> ask for cookies -> proceed with chain -> receive cookies dao callback -> add header to builder which has been already used
What you need to do is retrieve the cookies synchronously, to accomplish this you can use the BlockingObseervable and get something like this.
Using a synchronous function won't cause any trouble since the interceptor is already running on a background thread.
#SuppressLint("CheckResult")
override fun intercept(chain: Interceptor.Chain): Response {
val builder = chain.request().newBuilder()
val cookies = cookiesDao.getAll().toBlocking().first()
builder.addHeader("Cookie", "JWT=" + cookies.jwt)
return chain.proceed(builder.build())
}

OkHttpClient injected with Koin loses Authorization header

I'm adding DI to the existing project, in process I faced problem that header Authorization disappears from request. There is no any exceptions or logs from Retrofit/OkHttp. My dependencies are:
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
implementation 'com.squareup.okhttp:okhttp:2.7.5'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'org.koin:koin-android:2.1.3'
I create http client using provideClient:
class OkHttpProvider private constructor() {
companion object {
fun provideClient(credentials: UsernamePasswordCredentials? = null, context: Context): OkHttpClient {
val client = OkHttpClient.Builder()
// logs
if (BuildConfig.DEBUG) {
client.addInterceptor(
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
)
}
if (credentials != null) {
val creds = Credentials.basic(credentials.userName, credentials.password)
val headerInterceptor = Interceptor { chain ->
var request = chain.request()
val headers = request
.headers()
.newBuilder()
.add("Authorization", creds)
.build()
request = request.newBuilder().headers(headers).build()
chain.proceed(request)
}
//client.addInterceptor(AccessTokenInterceptor(credentials))
client.addInterceptor(headerInterceptor)
}
client
.callTimeout(60L, TimeUnit.SECONDS)
.connectTimeout(10L, TimeUnit.SECONDS)
.readTimeout(60L, TimeUnit.SECONDS)
.writeTimeout(60L, TimeUnit.SECONDS)
.sslSocketFactory(getSslContext().socketFactory).hostnameVerifier { _, _ -> true }
client.addInterceptor(ChuckInterceptor(context))
return client.build()
}
private fun getSslContext(): SSLContext {
...implementation...
}
}
}
My modules for http client and Retrofit are below:
object HttpClientModule {
val module = module {
single(named(COMMON)) {
OkHttpProvider.provideClient(
get<SharedPreferenceManager>().getUserCredentials(),
androidContext()
)
}
...other versions...
}
const val COMMON = "common"
}
object ApiModule {
val module = module {
single {
RetrofitFactory.getServiceInstance(
ApiService::class.java,
get<SharedPreferenceManager>().getString(LocalDataSource.BUILD_OPTION_API, ""),
get(named(HttpClientModule.COMMON))
)
}
...other apis...
}
}
object RetrofitFactory {
const val GEO_URL = "http://maps.googleapis.com/maps/api/"
fun <T> getServiceInstance(
clazz: Class<T>,
url: String = GEO_URL,
client: OkHttpClient
): T = getRetrofitInstance(url, client).create(clazz)
private fun getRetrofitInstance(
url: String,
client: OkHttpClient
) = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
}
App starts to work with "admin" user and has some credentials saved in shared preferences, when user starts login with phone and sms and requests are sent with "admin" Authorization header, when user inputs code from sms and his new user credentials are saved in shared preferences. After that app sends two requests and Authorization header isn't presented in them. I saw it in Chuck, I even rechecked it using Charles.
To fix this problem I tried few solutions. Firstly, I changed inject for http client from single to factory, that didn't work. Secondly, I googled the problem, but I didn't mentions of this phenomenon. Thirdly, I wrote AccessTokenInterceptor according to this article and also cover everything with logs. I noticed that interceptor works fine in normal cases, but when Authorization header is missing method intercept is not called. This might be reason why default headerInterceptor also not working. Fourthly, I upgraded versions of Retrofit and OkHttp, this also didn't helped.
I noticed interesting thing about that bug: if I restart app after Retrofit lost Authorization header, app works fine test user is properly logged with correct token. Any attempts to relog without restarting the app fails. Maybe someone had similar problem or knows what is happening here, any ideas are welcomed.
I finally find solution to this problem. The problem was user credentials was passed to provideClient only once, when it's created. At that moment user was logged as admin, and standard user credentials was empty, so http client for ApiService was created without Authorization header.
To solve this I changed AccessTokenInterceptor form article (HttpClientType is a enum to select which credentials need to use):
class AccessTokenInterceptor(
private val sharedPreferenceManager: SharedPreferenceManager,
private val clientType: OkHttpProvider.HttpClientType
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val credentials = getUserCredentials(clientType)
if (credentials != null) {
val accessToken = Credentials.basic(credentials.userName, credentials.password)
val request = newRequestWithAccessToken(chain.request(), accessToken)
return chain.proceed(request)
} else {
return chain.proceed(chain.request())
}
}
private fun getUserCredentials(clientType: OkHttpProvider.HttpClientType): UsernamePasswordCredentials? {
return when (clientType) {
OkHttpProvider.HttpClientType.COMMON -> sharedPreferenceManager.getUserCredentials()
OkHttpProvider.HttpClientType.ADMIN -> ServiceCredentialsUtils.getCredentials(sharedPreferenceManager)
}
}
private fun newRequestWithAccessToken(#NonNull request: Request, #NonNull accessToken: String): Request {
return if (request.header("Authorization") == null) {
request.newBuilder()
.header("Authorization", accessToken)
.build()
} else {
request
}
}
}
Now each time request is sending, Interceptor gets user's credentials and adds header to request.

OkHttp Interceptor chain broken when getting token

I have an OkHttp Interceptor which should ask for a token when the request is getting a 401 HTTP error. Now, the request to login service is done but then the chain is broken and the original request is not retried.
Here is the intercept method of my interceptor:
override fun intercept(chain: Interceptor.Chain): Response {
logger.d("AuthenticationServiceHolder $authenticationServiceHolder")
val originalRequest = chain.request()
logger.d("Intercepting call to ${originalRequest.method()} ${originalRequest.url()}")
val response: Response = chain.proceed(originalRequest)
val successful = response.isSuccessful
val code = response.code()
logger.d("Response successful: $successful - code: $code")
if (!successful && code == HttpURLConnection.HTTP_UNAUTHORIZED) {
logger.d("Token is $token")
val deviceUuid = deviceIdentificationManager.deviceUuid().blockingGet()
logger.d("Device uuid $deviceUuid")
if (deviceUuid != null) {
val authenticationService = authenticationServiceHolder.get()
if (authenticationService != null) {
token = reLogin(authenticationService, deviceUuid)
if (token != null) {
val headersBuilder = originalRequest.headers().newBuilder()
headersBuilder.removeAll(AUTHORIZATION_HEADER)
headersBuilder.add(AUTHORIZATION_HEADER, token!!)
val requestBuilder = originalRequest.newBuilder()
val request = requestBuilder.headers(headersBuilder.build()).build()
return chain.proceed(request)
} else {
logger.e("Token was not retrieved")
}
} else {
logger.e("Authentication service is null!")
}
}
}
return response
}
The reLogin() method is:
private fun reLogin(authenticationService: AuthenticationService, deviceUuid: UUID): String? {
logger.d("reLogin() - authenticationService $authenticationService")
val blockingGet = authenticationService?.login(LoginRequest(deviceUuid, clock.currentTime()))?.blockingGet()
logger.d("reLogin() - response $blockingGet")
val response = blockingGet ?: return null
logger.d("reLogin() - token ${response.token}")
return response.token
}
NEW:
As Mitesh Machhoya says, I've tried with 2 different instances of retrofit, one has the okhttp client with the interceptor and the another doesn't have it.
And now the login call is not intercepted but the execution of the Interceptor is broken, I mean the log trace of this class is:
- AuthenticationServiceHolder XXXmypackageXXX.AuthenticationServiceHolder...
- Intercepting call to GET XXXmyInterceptedCallXXX
- Response successful: false - code: 401
- Token is null
- Device uuid XXX
- reLogin() - authenticationService retrofit2.Retrofit$1#a5c0a25
And nothing more. I mean reLogin() - response..... is not printed. I'm sure that the login call is working because I see the login response in okhttp log.
Make reLogin request with other httpClient without attaching interceptor, then it will work well as you expected.
if you make reLogin request with same httpClient then it will gone through the interceptor and it override request everytime so try to make request using another httpClient
The code pasted is working well, the Login request is working but the response of login was changed on server side and the deserialisation made it crash and it broke the chain.

How to stop Okhttp Authenticator from being called multiple times?

I have an Authenticator like this
#Singleton
class TokenAutheticator #Inject constructor(private val tokenHolder: Lazy<TokenHolder>,private val tokenInterceptor: TokenInterceptor):Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
val resp = tokenHolder.get().tokenService.relogin(tokenInterceptor.token).execute()
println("### res "+resp.code())
if (resp.code()==200) {
val body = tokenHolder.get().tokenService.relogin(tokenInterceptor.token).execute()?.body()
val newToken = body?.token
println("########## authenticator ########## ")
val url = route?.address()?.url()?.newBuilder()?.addQueryParameter("token", newToken)?.build()
return response.request().newBuilder().url(url).build()
}else{
return null
}
}
}
When the resp.code != 200 the Authenticator is called multiple times.
I am plugging it in Okhttp like this
#Provides
#Singleton
fun provideOkhttp(tokenInterceptor: TokenInterceptor, tokenAutheticator: TokenAutheticator): OkHttpClient {
val logging = HttpLoggingInterceptor()
logging.setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder()
.authenticator(tokenAutheticator)
.addInterceptor(logging)
.addInterceptor(tokenInterceptor)
.build()
return client
}
So what I want to do is have the Authenticator try it only once and if it is able to get a new token then use the new token from now on and if it can't get a new token then exit. But the Authenticator is called multiple times and the API responds with Too many attempts. Any help is appreciated. Thanks
Only when you return null, Authenticator will stop getting called (stop retrying authentication).
Since you always return something, when response code is 200, it will get called a few times. Luckily, as far I understand, Authenticator detects your endless loop, and breaks out of it eventually.
Basically, you should use Authenticator to react to 401 (and similar) response code and only add authorization header in that case.

Categories

Resources