How to Display a Web Application with Basic Authentication in WebView using Jetpack Compose (Android)

akirakashihara

Akira Kashihara

Posted on June 9, 2022

How to Display a Web Application with Basic Authentication in WebView using Jetpack Compose (Android)

This article shows how to display a web application with Basic Authentication in WebView using Jetpack Compose.
The sample code on this article was made with reference to the thread on StackOverflow. StackOverflow's code is written in Java, but this article shows you the sample code in kotlin.

Source Code

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{ MyWebClient(url = "https://hogehoge.hoge")}
    }
}

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun MyWebClient(url: String) {

    AndroidView(factory = ::WebView,
    update = { webView ->
        webView.webViewClient = MyWebViewClient()
        webView.settings.javaScriptEnabled = true
        webView.loadUrl(url)

    })
}

// Ovverride onReceivedHttpAuthRequest in new class which extends WebViewClient().
private class MyWebViewClient: WebViewClient() {
    @Override
    override fun onReceivedHttpAuthRequest(
        view: WebView?,
        handler: HttpAuthHandler?,
        host: String?,
        realm: String?
    ) {
        if (handler != null) {
            handler.proceed("The user name to Basic Auth.", "The password to Basic Auth.")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The Result

I cannot show you the contents of the web application. But I guess that you can check that all contents (text and images) are loaded.

The Preview of Execution


This original article is the following that is written by me. This is a translation of a portion of this original article from Japanese to English.

💖 💪 🙅 🚩
akirakashihara
Akira Kashihara

Posted on June 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related