简体   繁体   中英

Differentiating HTTPOnly cookies from other in android

In my current project we are implementing session handling between Android application and server. Now by our design Android application should accept only HTTP Cookies and remove all other cookies. But looking at all the available option I couldn't find any class or method which help me to identify whether cookie is HTTPOnly or not.

I am storing cookies in following way:

        connections = (HttpURLConnection) serverURL.openConnection();
        // Setting cookies manager
        java.net.CookieManager manager = new java.net.CookieManager();
        manager.setCookiePolicy(new CookiePolicy() {

            @Override
            public boolean shouldAccept(URI uri, HttpCookie cookie) {
                return cookie.getSecure();
            }
        });
        CookieHandler.setDefault(manager);

        connections.setDoInput(true);
        connections.setDoOutput(true);
        connections.setConnectTimeout(TIME_OUT);

        connections.getOutputStream().write(data);

        InputStream inputStream = connections.getInputStream();
        CookieStore cookieJar = manager.getCookieStore();
        if (cookieJar != null) {
            List<HttpCookie> cookies = cookieJar.getCookies();
            for (HttpCookie httpCookie : cookies) {

                Log.i("yash", httpCookie.toString());
            }
        }

But this HttpCookie doesn't have any HTTPOnly method.

By some google browing I find out that RFC 6265 has HTTPOnly attribute and it also obsulate RFC 2965. But Why google has not supported this RFC 6265?

According to the class documentation HttpOnly is supported but for some reason there isn't any accessor nor mutator for this field.

To be able to access and modify the httpOnly field you should use reflection:

// Workaround httpOnly (getter)
private boolean getHttpOnly() {
    try {
        Field fieldHttpOnly = cookie.getClass().getDeclaredField("httpOnly");
        fieldHttpOnly.setAccessible(true);

        return (boolean) fieldHttpOnly.get(cookie);
    } catch (Exception e) {
        // NoSuchFieldException || IllegalAccessException ||
        // IllegalArgumentException
        Log.w(TAG, e);
    }
    return false;
}

// Workaround httpOnly (setter)
private void setHttpOnly(boolean httpOnly) {
    try {
        Field fieldHttpOnly = cookie.getClass().getDeclaredField("httpOnly");
        fieldHttpOnly.setAccessible(true);

        fieldHttpOnly.set(cookie, httpOnly);
    } catch (Exception e) {
        // NoSuchFieldException || IllegalAccessException ||
        // IllegalArgumentException
        Log.w(TAG, e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM