Search code examples
cookiessession-cookiesbasic-authenticationokhttp

Android OkHttp Basic Auth with session cookie


I am using OkHttp 3.x, and I need to authenticate to a server via Basic Auth. The server returns a JSESSIONID cookie upon successful authentication.

I have setup a CookieJar to store the returned cookie, and to send it back to the server (and it is well received).

However, at the moment I send the credentials via headers, and even though i send the cookie, the Basic Auth credentials are still sent.

How can I send the Basic Auth credentials only if the cookie is not set ? I would like to avoid using reactive authentication to avoid generating 401 on the server.


Solution

  • The easiest way to strip an unwanted header is with an interceptor. Check for the presence of the cookie, and strip the Authorization header if the cookie is present.