Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ allprojects {
url 'https://pkgs.dev.azure.com/MicrosoftDeviceSDK/DuoSDK-Public/_packaging/Duo-SDK-Feed/maven/v1'
name 'Duo-SDK-Feed'
}
maven {
url = "https://prove.jfrog.io/artifactory/libs-public-maven/"
}
mavenCentral()
google()
}
Expand All @@ -31,6 +34,7 @@ android {
buildFeatures {
viewBinding true
}
kotlinOptions { jvmTarget = '1.8' }
buildTypes {
release {
minifyEnabled false
Expand Down Expand Up @@ -83,4 +87,6 @@ dependencies {
// Downloads and Builds MSAL from maven central.
implementation 'com.microsoft.identity.client:msal:[8.1.0,)'
}

implementation 'com.prove.sdk:proveauth:6.9.0'
}
13 changes: 12 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,17 @@

<dist:module dist:instant="true" />

<!-- Required to perform authentication -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Required to access information about networks -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Required for ConnectivityManager.requestNetwork -->
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_title"
Expand All @@ -26,7 +36,8 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.microsoft.identity.client.BrowserTabActivity">
<activity android:name="com.microsoft.identity.client.BrowserTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />

Expand Down
6 changes: 6 additions & 0 deletions app/src/main/assets/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"Prove": {
"clientId": "nativeauthfraudcheck-poc-e7971c6c-c35b-4e17-80f8-99aefdb611c0-1770372962304",
"clientSecret": "CgvbgUQpZ95TXZOkYgi3TgOs1MITJj6L"
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we remove clientSecret from public sample?

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,8 @@ object AuthClient : Application() {
context,
R.raw.auth_config_native_auth
)

// Initialize Prove Bot Detection SDK
ProveBotDetectionHelper.initialize(context)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.azuresamples.msalnativeauthandroidkotlinsampleapp

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
Expand Down Expand Up @@ -97,6 +98,27 @@ class EmailPasswordSignInSignUpFragment : Fragment() {
val password = CharArray(binding.passwordText.length())
binding.passwordText.text?.getChars(0, binding.passwordText.length(), password, 0)

// Prove Bot Detection Gate
val phoneNumber = email // Replace with actual phone number field if available
if (ProveBotDetectionHelper.hasProveKey()) {
val botResult = ProveBotDetectionHelper.performBotDetection(phoneNumber)
when (botResult) {
is ProveBotDetectionHelper.BotDetectionResult.Failed -> {
binding.passwordText.text?.clear()
StringUtil.overwriteWithNull(password)
displayDialog("Fraud Detection", "Sign-in blocked: ${botResult.reason}")
return@launch
}
is ProveBotDetectionHelper.BotDetectionResult.Error -> {
Log.w(TAG, "Bot detection error: ${botResult.message}")
// Continue on error — adjust policy as needed
}
is ProveBotDetectionHelper.BotDetectionResult.Passed -> {
Log.i(TAG, "Bot detection passed. Proceeding with sign-in.")
}
}
}

val parameters = NativeAuthSignInParameters(username = email)
parameters.password = password
val actionResult: SignInResult = authClient.signIn(parameters)
Expand Down Expand Up @@ -137,6 +159,27 @@ class EmailPasswordSignInSignUpFragment : Fragment() {
val password = CharArray(binding.passwordText.length())
binding.passwordText.text?.getChars(0, binding.passwordText.length(), password, 0)

// Prove Bot Detection Gate
val phoneNumber = email // Replace with actual phone number field if available
if (ProveBotDetectionHelper.hasProveKey()) {
val botResult = ProveBotDetectionHelper.performBotDetection(phoneNumber)
when (botResult) {
is ProveBotDetectionHelper.BotDetectionResult.Failed -> {
binding.passwordText.text?.clear()
StringUtil.overwriteWithNull(password)
displayDialog("Fraud Detection", "Sign-up blocked: ${botResult.reason}")
return@launch
}
is ProveBotDetectionHelper.BotDetectionResult.Error -> {
Log.w(TAG, "Bot detection error: ${botResult.message}")
// Continue on error — adjust policy as needed
}
is ProveBotDetectionHelper.BotDetectionResult.Passed -> {
Log.i(TAG, "Bot detection passed. Proceeding with sign-up.")
}
}
}

val parameters = NativeAuthSignUpParameters(username = email)
parameters.password = password
val actionResult: SignUpResult = authClient.signUp(parameters)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.azuresamples.msalnativeauthandroidkotlinsampleapp

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
Expand Down Expand Up @@ -94,6 +95,25 @@ class EmailSignInSignUpFragment : Fragment() {
CoroutineScope(Dispatchers.Main).launch {
val email = binding.emailText.text.toString()

// Prove Bot Detection Gate
val phoneNumber = email // Replace with actual phone number field if available
if (ProveBotDetectionHelper.hasProveKey()) {
val botResult = ProveBotDetectionHelper.performBotDetection(phoneNumber)
when (botResult) {
is ProveBotDetectionHelper.BotDetectionResult.Failed -> {
displayDialog("Fraud Detection", "Sign-in blocked: ${botResult.reason}")
return@launch
}
is ProveBotDetectionHelper.BotDetectionResult.Error -> {
Log.w(TAG, "Bot detection error: ${botResult.message}")
// Continue on error — adjust policy as needed
}
is ProveBotDetectionHelper.BotDetectionResult.Passed -> {
Log.i(TAG, "Bot detection passed. Proceeding with sign-in.")
}
}
}

val parameters = NativeAuthSignInParameters(username = email)
val actionResult = authClient.signIn(parameters)

Expand Down Expand Up @@ -125,6 +145,25 @@ class EmailSignInSignUpFragment : Fragment() {
CoroutineScope(Dispatchers.Main).launch {
val email = binding.emailText.text.toString()

// Prove Bot Detection Gate
val phoneNumber = email // Replace with actual phone number field if available
if (ProveBotDetectionHelper.hasProveKey()) {
val botResult = ProveBotDetectionHelper.performBotDetection(phoneNumber)
when (botResult) {
is ProveBotDetectionHelper.BotDetectionResult.Failed -> {
displayDialog("Fraud Detection", "Sign-up blocked: ${botResult.reason}")
return@launch
}
is ProveBotDetectionHelper.BotDetectionResult.Error -> {
Log.w(TAG, "Bot detection error: ${botResult.message}")
// Continue on error — adjust policy as needed
}
is ProveBotDetectionHelper.BotDetectionResult.Passed -> {
Log.i(TAG, "Bot detection passed. Proceeding with sign-up.")
}
}
}

val parameters = NativeAuthSignUpParameters(username = email)
val actionResult = authClient.signUp(parameters)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import com.microsoft.identity.nativeauth.statemachine.states.RegisterStrongAuthS
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Arrays

class MFAFragment : Fragment() {

Expand Down Expand Up @@ -100,6 +101,7 @@ class MFAFragment : Fragment() {

val parameters = NativeAuthSignInParameters(username = email)
parameters.password = password
parameters.scopes = Arrays.asList("openid", "offline_access", "profile", "api://019f8c18-e680-43b3-9ac3-d9e118b69c0d/App.Read")
val actionResult: SignInResult = authClient.signIn(parameters)
binding.passwordText.text?.clear()
StringUtil.overwriteWithNull(password)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.azuresamples.msalnativeauthandroidkotlinsampleapp

import android.app.Application
import android.util.Log
import org.json.JSONObject

class MainApplication : Application() {

override fun onCreate() {
super.onCreate()

Log.d("MS", "Application onCreate called")
initializeProveIfConfigured()
}

private fun initializeProveIfConfigured() {
// Read Prove credentials directly from the packaged config file:
// `app/src/main/assets/config.json`
val (clientId, clientSecret) = try {
val jsonText = assets.open("config.json").bufferedReader().use { it.readText() }
val proveJson = JSONObject(jsonText).optJSONObject("Prove")
val id = proveJson?.optString("clientId").orEmpty().trim()
val secret = proveJson?.optString("clientSecret").orEmpty().trim()
id to secret
} catch (t: Throwable) {
Log.e("MS", "Failed to read Prove config from assets/config.json", t)
"" to ""
}

if (clientId.isBlank() || clientSecret.isBlank()) {
Log.w(
"MS",
"Prove not initialized. Set Prove.clientId and Prove.clientSecret in app/src/main/assets/config.json."
)
return
}

ProveManager.getInstance().initialize(
clientId = clientId,
clientSecret = clientSecret
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package com.azuresamples.msalnativeauthandroidkotlinsampleapp

import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
* Helper class for integrating Prove Bot Detection into the sign-in/sign-up flows.
*
* Flow overview (per https://developer.prove.com/docs/check-for-prove-key#prompt-for-phone-number-3):
* 1. Initialize the Prove SDK on app start to obtain a device-level "Prove Key".
* 2. Before sending an OTP / completing sign-in, call YOUR backend with the phone number + Prove Key.
* 3. Your backend calls Prove's /v3/verify API with verificationType="bot".
* 4. The backend returns the bot-detection result to the app.
* 5. The app decides whether to proceed with authentication or block the attempt.
*/
object ProveBotDetectionHelper {

private const val TAG = "ProveBotDetection"

// IMPORTANT: Replace with your own backend endpoint that proxies to Prove's API.
// NEVER call Prove's API directly from the client — your access token must stay server-side.
private const val BOT_DETECTION_BACKEND_URL = "https://your-backend.example.com/api/prove/bot-detect"

private val httpClient = OkHttpClient()
private var proveKey: String? = null

/**
* Initialize the Prove SDK and retrieve the Prove Key (device fingerprint).
* Call this once during app startup (e.g., in AuthClient.initialize).
*/
fun initialize(context: Context) {
try {
// Initialize the Prove SDK — the exact API depends on the SDK version.
// Refer to: https://developer.prove.com/reference/unify-android-sdk
//
// Example (pseudocode — adapt to actual SDK):
// ProveAuth.initialize(context, "YOUR_PROVE_CLIENT_ID")
// proveKey = ProveAuth.getDeviceId()

Log.i(TAG, "Prove SDK initialized. Prove Key obtained.")

// TODO: Replace the line below with real SDK call
// proveKey = ProveAuth.getDeviceId()
proveKey = "PLACEHOLDER_PROVE_KEY" // Remove this after real integration
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize Prove SDK", e)
}
}

/**
* Check whether the Prove Key is available.
*/
fun hasProveKey(): Boolean {
return !proveKey.isNullOrBlank()
}

/**
* Perform bot detection by calling YOUR backend with the phone number and Prove Key.
*
* Your backend should:
* 1. Obtain a Prove access token (OAuth2 client_credentials grant).
* 2. POST to https://platform.prove.com/v3/verify with:
* {
* "verificationType": "bot",
* "phoneNumber": "<phone>",
* "deviceId": "<proveKey>",
* "clientRequestId": "<unique-session-id>"
* }
* 3. Return the result to the mobile app.
*
* @param phoneNumber The phone number entered by the user (E.164 format recommended)
* @return BotDetectionResult indicating whether the user passed or failed bot detection
*/
suspend fun performBotDetection(phoneNumber: String): BotDetectionResult {
if (!hasProveKey()) {
Log.w(TAG, "Prove Key not available. Cannot perform bot detection.")
return BotDetectionResult.Error("Prove Key not available. Please restart the app.")
}

return withContext(Dispatchers.IO) {
try {
val requestBody = JSONObject().apply {
put("phoneNumber", phoneNumber)
put("deviceId", proveKey)
put("clientRequestId", java.util.UUID.randomUUID().toString())
}.toString()

val request = Request.Builder()
.url(BOT_DETECTION_BACKEND_URL)
.post(requestBody.toRequestBody("application/json".toMediaType()))
.build()

val response = httpClient.newCall(request).execute()

if (response.isSuccessful) {
val responseBody = response.body?.string() ?: "{}"
val json = JSONObject(responseBody)

val isHuman = json.optBoolean("success", false)
val score = json.optDouble("score", 0.0)

if (isHuman) {
Log.i(TAG, "Bot detection passed. Score: $score")
BotDetectionResult.Passed(score)
} else {
Log.w(TAG, "Bot detection failed. Score: $score")
BotDetectionResult.Failed(score, "Phone number flagged as potential fraud.")
}
} else {
Log.e(TAG, "Bot detection API returned ${response.code}")
BotDetectionResult.Error("Bot detection service unavailable (HTTP ${response.code}).")
}
} catch (e: Exception) {
Log.e(TAG, "Bot detection request failed", e)
BotDetectionResult.Error("Bot detection failed: ${e.message}")
}
}
}

/**
* Sealed class representing the result of a bot detection check.
*/
sealed class BotDetectionResult {
/** The phone number passed bot detection (appears to be a real human). */
data class Passed(val score: Double) : BotDetectionResult()

/** The phone number failed bot detection (potential bot/fraud). */
data class Failed(val score: Double, val reason: String) : BotDetectionResult()

/** An error occurred during bot detection. */
data class Error(val message: String) : BotDetectionResult()
}
}
Loading