Giter Site home page Giter Site logo

gotev / android-cookie-store Goto Github PK

View Code? Open in Web Editor NEW
191.0 5.0 17.0 259 KB

Android InMemory and persistent Cookie Store for HttpURLConnection and OkHttp, with extensions to easily sync cookies in Android WebViews.

License: Apache License 2.0

Kotlin 97.02% Shell 2.98%
android cookie store httpurlconnection okhttp library kotlin webview

android-cookie-store's Introduction

Android Cookie Store

Android Arsenal Android Weekly ktlint Maven Central PRs Welcome

Android InMemory and persistent Cookie Store for HttpURLConnection and OkHttp, with extensions to easily sync cookies in Android WebViews.

Why?

Neither HttpURLConnection nor OkHttp provides a native and rapid way of storing cookies persistently on Android. This library aims to fill this gap, by implementing the standard java.net.InMemoryCookieStore in Kotlin, with extendability in mind.

With this library you have:

  • super tiny footprint (the library is only a bunch of classes)
  • an in memory only cookie store
  • a shared preferences backed cookie store which can survive app reboots
  • possibility to extend both to provide your own custom implementation which best fits your needs without reinventing the wheel for cookie management

Compatibility

Android API 16+

Getting started

Add this to your dependencies:

implementation "net.gotev:cookie-store:x.y.z"

Replace x.y.z with Maven Central

Usage

Create your Cookie Manager:

// Example extension function to demonstrate how to create both cookie stores
fun Context.createCookieStore(name: String, persistent: Boolean) = if (persistent) {
    SharedPreferencesCookieStore(applicationContext, name)
} else {
    InMemoryCookieStore(name)
}

val cookieManager = CookieManager(
    createCookieStore(name = "myCookies", persistent = true),
    CookiePolicy.ACCEPT_ALL
)

HttpURLConnection

To setup the default Cookie Manager:

CookieManager.setDefault(cookieManager)

OkHttp

Add the following dependency (suitable for JVM and Android):

implementation "net.gotev:cookie-store-okhttp:$cookieStoreVersion"

And when you build your OkHttpClient, set the Cookie Jar:

val okHttpClient = OkHttpClient.Builder()
    .cookieJar(JavaNetCookieJar(cookieManager))
    .build()

WebView

It's a common thing to obtain a cookie from an API and to open an authenticated web page inside an app which needs the cookie. You can find a complete working example in the demo app.

You have two ways of doing this:

  • Using WebKitSyncCookieManager
  • Using standard java.net.CookieManager

Using WebKitSyncCookieManager

val cookieManager = WebKitSyncCookieManager(
    store = createCookieStore(name = "myCookies", persistent = true),
    cookiePolicy = CookiePolicy.ACCEPT_ALL,
    onWebKitCookieManagerError = { exception ->
        // This gets invoked when there's internal webkit cookie manager exceptions
        Log.e("COOKIE-STORE", "WebKitSyncCookieManager error", exception)
    }
)

Then follow standard instructions from the Usage section to setup HttpURLConnection or OkHttp according to your needs.

Incoming Cookies will be automatically synced to WebKit's CookieManager. Syncing is unidirectional from WebKitSyncCookieManager to android.webkit.CookieManager to have a single source of truth and to prevent attacks coming from URLs loaded in WebViews. If you need bi-directional sync, think twice before doing it.

To clear cookies:

cookieManager.removeAll()

This will clear both the CookieStore and WebKit's Cookie Manager.

Using standard java.net.CookieManager

Cookies syncing is entirely up to you and manual.

To copy all cookies from the cookie store to the WebKit Cookie Manager:

cookieManager.cookieStore.syncToWebKitCookieManager()

Remember to do this before loading any URL in your web view.

To remove all cookies from the Cookie Store:

cookieManager.cookieStore.removeAll()

To remove all cookies from WebKit Cookie Manager:

android.webkit.CookieManager.getInstance().removeAll()

That's all folks!

android-cookie-store's People

Contributors

abnegate avatar dependabot-preview[bot] avatar dependabot[bot] avatar gotev avatar jimmymorales avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

android-cookie-store's Issues

ConcurrentModificationException

happens on this line preferences.edit().putString(index.toString(), gson.toJson(cookies)).apply()

E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.light.finder, PID: 28247
    java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.next(ArrayList.java:860)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:96)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
        at com.google.gson.Gson.toJson(Gson.java:704)
        at com.google.gson.Gson.toJson(Gson.java:683)
        at com.google.gson.Gson.toJson(Gson.java:638)
        at com.google.gson.Gson.toJson(Gson.java:618)
        at com.light.finder.data.source.remote.SharedPreferencesCookieStore.add(SharedPreferencesCookieStore.kt:51)
        at java.net.CookieManager.put(CookieManager.java:360)
        at com.light.finder.data.source.remote.WebKitSyncCookieManager.put(WebKitSyncCookieManager.kt:24)
        at okhttp3.JavaNetCookieJar.saveFromResponse(JavaNetCookieJar.kt:38)
        at okhttp3.internal.http.HttpHeaders.receiveHeaders(HttpHeaders.kt:207)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:86)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:71)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
        at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184)
        at okhttp3.RealCall$AsyncCall.run(RealCall.kt:136)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

`HttpCookie.toSetCookieString()` doesn't honor expiration date of cookies

There seems to be a flaw in the creation of the expiration part of HttpCookie.toSetCookieString().

HttpCookie.maxAge is the amount of time from the moment the cookie is created to when it should expire. This duration isn't being translated to the string being generated by toSetCookieString(). The string has the time at which that method is called plus the maxAge. This means every time I call the function I get a different "expiry" value, leading to the chance that I actually send a cookie that has expired after syncing with a WebView.

Unfortunately, HttpCookie doesn't allow access to the whenCreated value to make calculating the true expiry date possible, no matter when you happen to call the method HttpCookie.toSetCookieString().

I have resolved this in a similar library by creating my own "Cookie" class and using it to generate an HttpCookie or okhttp(2|3).Cookie when needed. This new class contains the maxAge and a created timestamp that is accessible.

Proguard Support

When enabling Proguard, SharedPreferencesCookieStore is not parsing correctly saved preferences probably due to HttpCookie class being minified/obfuscate by Proguard.

I manage to fix it by adding -keep class java.net.HttpCookie { <fields>; } in my proguard-rules.pro file.

It will be great if this can be handle by the library or adding a Proguard section in the README.

Duplicating cookies

InMemoryCookieStore is not just kotlin-ized, you made mistake that getInternal1 and getInternal2 working on separate list which cause returned result contains duplicated cookies.

Fatal Exception: java.util.ConcurrentModificationException net.gotev.cookiestore.SharedPreferencesCookieStore.add

java.util.ArrayList$Itr.next (ArrayList.java:860)
com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write (CollectionTypeAdapterFactory.java:96)
com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write (CollectionTypeAdapterFactory.java:61)
com.google.gson.Gson.toJson (Gson.java:704)
com.google.gson.Gson.toJson (Gson.java:683)
com.google.gson.Gson.toJson (Gson.java:638)
com.google.gson.Gson.toJson (Gson.java:618)
net.gotev.cookiestore.SharedPreferencesCookieStore.add (SharedPreferencesCookieStore.java:54)
java.net.CookieManager.put (CookieManager.java:360)

Possible to use EncryptedSharedPreferences?

What are your thoughts on modifying/adding an implementation where the SharedPreferencesCookieStore uses an EncryptedSharedPreference? I tried to extend InMemoryCookieStore with my own implementation with EncryptedSharedPreference, but was unable to reference the underlying map of URIs and cookies (uriIndex)

with Android 12, HttpCookie does not get serialized properly with gson.toJson

In SharedPreferencesCookieStore.kt line 60:

gson.toJson(ArrayList(cookies)))

This is critical to serialize HttpCookie ArrayList to sharedPreferences.
Only httpOnly and whenCreated fields appear as BoundFields.
name and value of the cookie does not get written to prefs.

This bug renders the library useless above Android 12+

android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview

Caused by android.util.AndroidRuntimeException
android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview
android.webkit.WebViewFactory.getFactoryClass (WebViewFactory.java:195)
android.webkit.CookieManager.getInstance (CookieManager.java:42)
net.gotev.cookiestore.WebKitSyncCookieManager$webKitCookieManager$2.invoke (WebKitSyncCookieManager.java:14)
net.gotev.cookiestore.WebKitSyncCookieManager$webKitCookieManager$2.invoke (WebKitSyncCookieManager.java:8)
kotlin.SynchronizedLazyImpl.getValue (SynchronizedLazyImpl.java:74)
net.gotev.cookiestore.WebKitSyncCookieManager.getWebKitCookieManager (WebKitSyncCookieManager.java)

Cookie not storing across app reboots

I'm using OkHttp, and it saves cookies received while the app is still running, but once I close the app and restart, it no longer has the cookie.

// Example extension function to demonstrate how to create both cookie stores
    private fun createCookieStore(name: String, persistent: Boolean) = if (persistent) {
        context?.let { SharedPreferencesCookieStore(it, name) }
    } else {
        InMemoryCookieStore(name)
    }


    private val cookieManager = CookieManager(
        createCookieStore(name = "myCookies", persistent = true),
        CookiePolicy.ACCEPT_ALL
    )

    private val client = OkHttpClient.Builder()
        .cookieJar(JavaNetCookieJar(cookieManager))
        .build()

This is how I have the code implemented.

Fatal exception: concurrent modification exception

java.util.ArrayList$Itr.next (ArrayList.java:860) net.gotev.cookiestore.SharedPreferencesCookieStore.add (SharedPreferencesCookieStore.kt:107) java.net.CookieManager.put (CookieManager.java:360) net.gotev.cookiestore.WebKitSyncCookieManager.put (WebKitSyncCookieManager.kt:37)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.