-
Notifications
You must be signed in to change notification settings - Fork 131
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13487 from woocommerce/issue/13467-improve-authen…
…ticated-webview-2 Authenticated WebView improvement [Part 2]
- Loading branch information
Showing
23 changed files
with
663 additions
and
101 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
...src/main/kotlin/com/woocommerce/android/ui/common/webview/CanAutoAuthenticateInWebView.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package com.woocommerce.android.ui.common.webview | ||
|
||
import javax.inject.Inject | ||
|
||
/** | ||
* A utility use-case to allow consumers to know beforehand if a URL can be auto-authenticated in a WebView. | ||
*/ | ||
class CanAutoAuthenticateInWebView @Inject constructor( | ||
private val authenticationFlowResolver: WebViewAuthenticationFlowResolver | ||
) { | ||
operator fun invoke(url: String): Boolean { | ||
val authenticationFlow = authenticationFlowResolver.resolve(url) | ||
return authenticationFlow != WebViewAuthenticationFlowResolver.WebViewAuthenticationFlow.None | ||
} | ||
} |
66 changes: 66 additions & 0 deletions
66
...ain/kotlin/com/woocommerce/android/ui/common/webview/WebViewAuthenticationFlowResolver.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package com.woocommerce.android.ui.common.webview | ||
|
||
import androidx.annotation.VisibleForTesting | ||
import com.woocommerce.android.extensions.isNotNullOrEmpty | ||
import com.woocommerce.android.tools.SelectedSite | ||
import okhttp3.HttpUrl.Companion.toHttpUrl | ||
import org.wordpress.android.fluxc.model.SiteModel | ||
import org.wordpress.android.fluxc.store.AccountStore | ||
import javax.inject.Inject | ||
|
||
class WebViewAuthenticationFlowResolver @Inject constructor( | ||
private val selectedSite: SelectedSite, | ||
private val accountStore: AccountStore | ||
) { | ||
// A list of domains that we know that wordpress.com supports redirecting to | ||
private val wpComAuthAcceptedDomains | ||
get() = listOf("wordpress.com", "wp.com", "jetpack.com", "woocommerce.com") | ||
|
||
fun resolve(url: String): WebViewAuthenticationFlow { | ||
val currentSite = selectedSite.getOrNull() | ||
val urlDomain = url.findDomain() | ||
val isWPComAuthenticated = accountStore.accessToken.isNotNullOrEmpty() && | ||
accountStore.account.userName.isNotNullOrEmpty() | ||
|
||
return if (isWPComAuthenticated) { | ||
when { | ||
wpComAuthAcceptedDomains.any { it == urlDomain } || | ||
(currentSite?.isWPComAtomic == true && url.isPartOf(currentSite)) -> { | ||
WebViewAuthenticationFlow.WPCom | ||
} | ||
|
||
currentSite?.supportsJetpackSSO() == true && url.isPartOf(currentSite) -> { | ||
WebViewAuthenticationFlow.JetpackSSO | ||
} | ||
|
||
else -> { | ||
WebViewAuthenticationFlow.None | ||
} | ||
} | ||
} else if (currentSite?.username.isNotNullOrEmpty() && | ||
currentSite.password.isNotNullOrEmpty() && | ||
url.isPartOf(currentSite) | ||
) { | ||
WebViewAuthenticationFlow.SiteCredentials | ||
} else { | ||
WebViewAuthenticationFlow.None | ||
} | ||
} | ||
|
||
@VisibleForTesting | ||
fun String.isPartOf(site: SiteModel): Boolean { | ||
// This is a simple check, so it could miss some edge cases, but it should be good enough for our use-case | ||
// We are using contains instead of equals to account for potential subdomains | ||
return findDomain().contains(site.url.findDomain()) | ||
} | ||
|
||
private fun String.findDomain(): String = toHttpUrl().host.substringAfter("www.") | ||
|
||
private fun SiteModel.supportsJetpackSSO(): Boolean { | ||
return jetpackModules?.contains("sso") == true | ||
} | ||
|
||
enum class WebViewAuthenticationFlow { | ||
WPCom, JetpackSSO, SiteCredentials, None | ||
} | ||
} |
145 changes: 117 additions & 28 deletions
145
...ommerce/src/main/kotlin/com/woocommerce/android/ui/common/webview/WebViewAuthenticator.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,51 +1,140 @@ | ||
package com.woocommerce.android.ui.common.webview | ||
|
||
import android.webkit.CookieManager | ||
import android.webkit.WebView | ||
import com.woocommerce.android.extensions.isNotNullOrEmpty | ||
import androidx.annotation.VisibleForTesting | ||
import com.woocommerce.android.extensions.loginUrlOrDefault | ||
import com.woocommerce.android.extensions.urlEncode | ||
import com.woocommerce.android.tools.SelectedSite | ||
import com.woocommerce.android.ui.compose.component.web.WCWebViewEvent | ||
import com.woocommerce.android.util.WooLog | ||
import kotlinx.coroutines.flow.Flow | ||
import kotlinx.coroutines.flow.first | ||
import kotlinx.coroutines.flow.firstOrNull | ||
import okhttp3.HttpUrl.Companion.toHttpUrl | ||
import org.wordpress.android.fluxc.store.AccountStore | ||
import java.io.UnsupportedEncodingException | ||
import java.net.URLEncoder | ||
import java.nio.charset.StandardCharsets | ||
import java.util.Locale | ||
import javax.inject.Inject | ||
|
||
private const val WPCOM_LOGIN_URL = "https://wordpress.com/wp-login.php" | ||
|
||
class WebViewAuthenticator @Inject constructor( | ||
private val accountStore: AccountStore | ||
private val authenticationFlowResolver: WebViewAuthenticationFlowResolver, | ||
private val selectedSite: SelectedSite, | ||
private val accountStore: AccountStore, | ||
private val webViewCookieManager: CookieManager | ||
) { | ||
fun authenticateAndLoadUrl(webView: WebView, url: String) { | ||
getAuthPostData(url).let { postData -> | ||
if (postData.isNotEmpty()) { | ||
webView.postUrl(WPCOM_LOGIN_URL, postData.toByteArray()) | ||
} else { | ||
suspend fun authenticateAndLoadUrl(webView: WebView, url: String, webViewEvents: Flow<WCWebViewEvent>) { | ||
val authenticationFlow = authenticationFlowResolver.resolve(url) | ||
when (authenticationFlow) { | ||
WebViewAuthenticationFlowResolver.WebViewAuthenticationFlow.WPCom -> { | ||
authenticateWPComAndLoad(webView, url) | ||
} | ||
|
||
WebViewAuthenticationFlowResolver.WebViewAuthenticationFlow.JetpackSSO -> { | ||
authenticateSSOAndLoad(webView, url, webViewEvents) | ||
} | ||
|
||
WebViewAuthenticationFlowResolver.WebViewAuthenticationFlow.SiteCredentials -> { | ||
authenticateUsingSiteCredentialsAndLoad(webView, url, webViewEvents) | ||
} | ||
|
||
WebViewAuthenticationFlowResolver.WebViewAuthenticationFlow.None -> { | ||
webView.loadUrl(url) | ||
} | ||
} | ||
} | ||
|
||
private fun authenticateWPComAndLoad(webView: WebView, url: String): Boolean { | ||
val postData = prepareLoginPostData( | ||
redirectUrl = url, | ||
username = accountStore.account.userName, | ||
authorizationParam = "authorization" to "Bearer ${accountStore.accessToken}" | ||
) | ||
|
||
if (postData != null) { | ||
webView.postUrl(WPCOM_LOGIN_URL, postData.toByteArray()) | ||
return true | ||
} else { | ||
webView.loadUrl(url) | ||
return false | ||
} | ||
} | ||
|
||
private suspend fun authenticateSSOAndLoad(webView: WebView, url: String, webViewEvents: Flow<WCWebViewEvent>) { | ||
authenticateWPComAndLoad(webView, JETPACK_SSO_TEMP_REDIRECT_URL).also { | ||
if (!it) { | ||
// The authentication failed, so load the original URL | ||
webView.loadUrl(url) | ||
return | ||
} | ||
} | ||
|
||
// Wait for the WPCom login to complete | ||
webViewEvents.first { it is WCWebViewEvent.PageFinished && it.url == JETPACK_SSO_TEMP_REDIRECT_URL } | ||
|
||
// Handle SSO login and redirect back to the original URL | ||
val site = selectedSite.get() | ||
webViewCookieManager.setCookie(site.url, "jetpack_sso_redirect_to=$url") | ||
val ssoLoginUrl = site.loginUrlOrDefault.toHttpUrl().newBuilder() | ||
.addQueryParameter("action", "jetpack-sso") | ||
.build() | ||
.toString() | ||
|
||
webView.loadUrl(ssoLoginUrl) | ||
} | ||
|
||
@Suppress("ReturnCount") | ||
private fun getAuthPostData(redirectUrl: String): String { | ||
val username = accountStore.account.userName.takeIf { it.isNotNullOrEmpty() } ?: return "" | ||
val token = accountStore.accessToken.takeIf { it.isNotNullOrEmpty() } ?: return "" | ||
private suspend fun authenticateUsingSiteCredentialsAndLoad( | ||
webView: WebView, | ||
url: String, | ||
webViewEvents: Flow<WCWebViewEvent> | ||
) { | ||
val site = selectedSite.get() | ||
|
||
val postData = prepareLoginPostData( | ||
redirectUrl = url, | ||
username = site.username, | ||
authorizationParam = "pwd" to site.password | ||
) | ||
|
||
if (postData != null) { | ||
webView.postUrl(site.loginUrlOrDefault, postData.toByteArray()) | ||
} else { | ||
webView.loadUrl(url) | ||
} | ||
|
||
val event = webViewEvents.firstOrNull { it is WCWebViewEvent.PageFinished || it is WCWebViewEvent.UrlFailed } | ||
if (event is WCWebViewEvent.UrlFailed && event.url == site.loginUrlOrDefault) { | ||
// In case we failed to authenticate, load the original URL | ||
// The failure could happen if some other security measures were added that would prevent | ||
// native handling of login (like using a custom login page or a captcha) | ||
WooLog.w(WooLog.T.UTILS, "Failed to authenticate the WebView using site credentials, load the original URL") | ||
webView.loadUrl(url) | ||
} | ||
} | ||
|
||
val utf8 = StandardCharsets.UTF_8.name() | ||
try { | ||
var postData = String.format( | ||
Locale.ROOT, | ||
"log=%s&redirect_to=%s", | ||
URLEncoder.encode(username, utf8), | ||
URLEncoder.encode(redirectUrl, utf8), | ||
) | ||
private fun prepareLoginPostData( | ||
redirectUrl: String, | ||
username: String, | ||
authorizationParam: Pair<String, String>, | ||
): String? { | ||
val (authorizationKey, authorizationValue) = authorizationParam | ||
return try { | ||
buildString { | ||
append("redirect_to=").append(redirectUrl.urlEncode()) | ||
|
||
// Add token authorization | ||
postData += "&authorization=Bearer " + URLEncoder.encode(token, utf8) | ||
append("&log=").append(username.urlEncode()) | ||
|
||
return postData | ||
append("&${authorizationKey.urlEncode()}=") | ||
.append(authorizationValue.urlEncode()) | ||
} | ||
} catch (e: UnsupportedEncodingException) { | ||
WooLog.e(WooLog.T.UTILS, e) | ||
null | ||
} | ||
return "" | ||
} | ||
|
||
companion object { | ||
@VisibleForTesting | ||
const val WPCOM_LOGIN_URL = "https://wordpress.com/wp-login.php" | ||
const val JETPACK_SSO_TEMP_REDIRECT_URL = "https://wordpress.com/mobile-redirect" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.