8

I need to open a web page in the custom tab. However, the page would obviously require users to log in. We don't want our users to be asked to log in, instead, we want to set cookies with token to CustomTab so that they will be automatically logged. I have read an answer here that says it is not possible. Do I understand it correctly? Is there a way to achieve the goal?

EDIT: I've tried this after @Aris Panayiotou's answer but it did not work. What did I do wrong here?

private void openWebView() {
    if (getActivity() != null) {
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager );
        String cookieStringTakenFromWeb = "some cookie string with correct token";

        CookieStore cookieStore = cookieManager.getCookieStore();
        HttpCookie cookie = new HttpCookie("Cookie", cookieStringTakenFromWeb);
        cookieStore.add(URI.create(Util.getString(R.string.myUrl)), cookie);

        final CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(mCustomTabsSession)
                .setToolbarColor(ContextCompat.getColor(getActivity(), R.color.red))
                .setShowTitle(true)
                .build();
        customTabsIntent.launchUrl(getActivity(), Uri.parse(Util.getString(R.string.myUrl)));
    }
}
Sermilion
  • 1,920
  • 3
  • 35
  • 54

2 Answers2

6

If you can update the website's code to read a header, you could pass the token in the request header.

val customTabsIntent = CustomTabsIntent.Builder(session).build()
val headersBundle = Bundle().apply {
    putString("X-Session-Token", "token")
}
customTabsIntent.intent.putExtra(android.provider.Browser.EXTRA_HEADERS, headersBundle)
starkej2
  • 11,391
  • 6
  • 35
  • 41
  • I was not able to see header being passed in the browser while I was inspecting it, but my website's frontend team was able to access the headers and set them as cookies on the browser. – Damanpreet Singh Mar 30 '21 at 07:56
-1

as of what i understand from your question, you can try CookieHandler. A CookieHandler object provides a callback mechanism to hook up a HTTP state management policy implementation into the HTTP protocol handler. The HTTP state management mechanism specifies a way to create a stateful session with HTTP requests and responses.

Read More on this link : CookieHandler

and CookieManager read more : CookieManager