@microsoft/power-apps-native-auth 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +112 -0
- package/README.md +54 -0
- package/android/build.gradle +79 -0
- package/android/src/main/AndroidManifest.xml +31 -0
- package/android/src/main/java/expo/modules/msalintune/ExpoMsalIntuneModule.kt +488 -0
- package/app.plugin.js +4 -0
- package/expo-module.config.json +9 -0
- package/ios/ExpoMsalIntune.podspec +27 -0
- package/ios/ExpoMsalIntuneAppDelegate.swift +31 -0
- package/ios/ExpoMsalIntuneModule.swift +382 -0
- package/lib/NOTICE.txt +5 -0
- package/lib/commonjs/AuthConfig.types.js +1 -0
- package/lib/commonjs/ExpoMsalIntune.types.js +1 -0
- package/lib/commonjs/ExpoMsalIntuneModule.js +50 -0
- package/lib/commonjs/index.js +217 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/module/AuthConfig.types.js +1 -0
- package/lib/module/ExpoMsalIntune.types.js +1 -0
- package/lib/module/ExpoMsalIntuneModule.js +44 -0
- package/lib/module/index.js +207 -0
- package/lib/module/package.json +1 -0
- package/lib/typescript/commonjs/AuthConfig.types.d.ts +76 -0
- package/lib/typescript/commonjs/ExpoMsalIntune.types.d.ts +80 -0
- package/lib/typescript/commonjs/ExpoMsalIntuneModule.d.ts +92 -0
- package/lib/typescript/commonjs/index.d.ts +125 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/module/AuthConfig.types.d.ts +76 -0
- package/lib/typescript/module/ExpoMsalIntune.types.d.ts +80 -0
- package/lib/typescript/module/ExpoMsalIntuneModule.d.ts +92 -0
- package/lib/typescript/module/index.d.ts +125 -0
- package/lib/typescript/module/package.json +1 -0
- package/package.json +93 -0
- package/plugin/index.js +528 -0
- package/plugin/withMsalRedirectScheme.js +53 -0
- package/scripts/setup-android-sdk.js +122 -0
- package/scripts/setup-ios-frameworks.js +100 -0
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
package expo.modules.msalintune
|
|
2
|
+
|
|
3
|
+
import expo.modules.kotlin.modules.Module
|
|
4
|
+
import expo.modules.kotlin.modules.ModuleDefinition
|
|
5
|
+
import expo.modules.kotlin.Promise
|
|
6
|
+
|
|
7
|
+
import com.microsoft.identity.client.*
|
|
8
|
+
import com.microsoft.identity.client.IPublicClientApplication.ISingleAccountApplicationCreatedListener
|
|
9
|
+
import com.microsoft.identity.client.ISingleAccountPublicClientApplication.CurrentAccountCallback
|
|
10
|
+
import com.microsoft.identity.client.exception.MsalException
|
|
11
|
+
import com.microsoft.identity.client.exception.MsalUiRequiredException
|
|
12
|
+
|
|
13
|
+
import android.content.pm.PackageManager
|
|
14
|
+
import android.os.Handler
|
|
15
|
+
import android.os.Looper
|
|
16
|
+
import android.util.Base64
|
|
17
|
+
import android.util.Log
|
|
18
|
+
import org.json.JSONArray
|
|
19
|
+
import org.json.JSONObject
|
|
20
|
+
import java.io.File
|
|
21
|
+
import java.security.MessageDigest
|
|
22
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
23
|
+
|
|
24
|
+
private const val TAG = "ExpoMsalIntune"
|
|
25
|
+
|
|
26
|
+
class ExpoMsalIntuneModule : Module() {
|
|
27
|
+
|
|
28
|
+
private var pca: IMultipleAccountPublicClientApplication? = null
|
|
29
|
+
|
|
30
|
+
override fun definition() = ModuleDefinition {
|
|
31
|
+
Name("ExpoMsalIntune")
|
|
32
|
+
|
|
33
|
+
// -------------------------------------------------------------------------
|
|
34
|
+
// initializeClient
|
|
35
|
+
// -------------------------------------------------------------------------
|
|
36
|
+
AsyncFunction("initializeClient") {
|
|
37
|
+
clientId: String,
|
|
38
|
+
authority: String,
|
|
39
|
+
redirectUri: String,
|
|
40
|
+
useEmbeddedWebView: Boolean,
|
|
41
|
+
useBroker: Boolean,
|
|
42
|
+
promise: Promise ->
|
|
43
|
+
|
|
44
|
+
// MSAL only needs the application context (not the Activity) to create
|
|
45
|
+
// the PCA. Using reactContext.applicationContext avoids a race where
|
|
46
|
+
// currentActivity is null during early JS startup.
|
|
47
|
+
val appCtx = appContext.reactContext?.applicationContext
|
|
48
|
+
?: return@AsyncFunction promise.reject("E_NO_CONTEXT", "No application context available", null)
|
|
49
|
+
|
|
50
|
+
val configJson = buildMsalConfigJson(
|
|
51
|
+
clientId = clientId,
|
|
52
|
+
authority = authority,
|
|
53
|
+
redirectUri = redirectUri,
|
|
54
|
+
useEmbeddedWebView = useEmbeddedWebView,
|
|
55
|
+
useBroker = useBroker,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
// MSAL Android requires config as a File or raw resource — there is no
|
|
59
|
+
// API to pass a JSONObject directly. Write to a fixed file in the app
|
|
60
|
+
// cache (overwriting each time). Using a fixed name avoids accumulating
|
|
61
|
+
// temp files: deleteOnExit() is a no-op on Android since the JVM shutdown
|
|
62
|
+
// hook never runs when the process is killed by the OS.
|
|
63
|
+
val configFile = File(appCtx.cacheDir, "msal_config.json")
|
|
64
|
+
configFile.writeText(configJson.toString())
|
|
65
|
+
Log.d(TAG, "initializeClient: config written, starting PCA creation")
|
|
66
|
+
|
|
67
|
+
// Under Bridgeless / New Architecture, createMultipleAccountPublicClientApplication
|
|
68
|
+
// can hang indefinitely when the MSAL SharedPreferences cache is corrupted
|
|
69
|
+
// (e.g. left in a bad state after a prior failed signout). The callback
|
|
70
|
+
// (onCreated / onError) never fires, so isLoading stays true forever.
|
|
71
|
+
//
|
|
72
|
+
// Fix: set an 8-second deadline. On timeout, wipe all MSAL/ADAL/identity
|
|
73
|
+
// SharedPreferences files (clearing the corruption) and retry once.
|
|
74
|
+
val settled = AtomicBoolean(false)
|
|
75
|
+
val mainHandler = Handler(Looper.getMainLooper())
|
|
76
|
+
|
|
77
|
+
fun clearMsalCache() {
|
|
78
|
+
try {
|
|
79
|
+
val prefsDir = File(appCtx.applicationInfo.dataDir, "shared_prefs")
|
|
80
|
+
prefsDir.listFiles()
|
|
81
|
+
?.filter { f ->
|
|
82
|
+
f.name.contains("msal", ignoreCase = true) ||
|
|
83
|
+
f.name.contains("identity", ignoreCase = true) ||
|
|
84
|
+
f.name.contains("adal", ignoreCase = true)
|
|
85
|
+
}
|
|
86
|
+
?.forEach { f ->
|
|
87
|
+
Log.w(TAG, "initializeClient: clearing corrupted cache file: ${f.name}")
|
|
88
|
+
f.delete()
|
|
89
|
+
}
|
|
90
|
+
} catch (e: Exception) {
|
|
91
|
+
Log.w(TAG, "initializeClient: failed to clear MSAL cache: ${e.message}")
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
fun createPca(
|
|
96
|
+
onSuccess: (IMultipleAccountPublicClientApplication) -> Unit,
|
|
97
|
+
onFailure: (MsalException) -> Unit,
|
|
98
|
+
) {
|
|
99
|
+
PublicClientApplication.createMultipleAccountPublicClientApplication(
|
|
100
|
+
appCtx,
|
|
101
|
+
configFile,
|
|
102
|
+
object : IPublicClientApplication.IMultipleAccountApplicationCreatedListener {
|
|
103
|
+
override fun onCreated(application: IMultipleAccountPublicClientApplication) {
|
|
104
|
+
Log.d(TAG, "initializeClient: PCA onCreated")
|
|
105
|
+
onSuccess(application)
|
|
106
|
+
}
|
|
107
|
+
override fun onError(exception: MsalException) {
|
|
108
|
+
Log.e(TAG, "initializeClient: PCA onError: ${exception.message}")
|
|
109
|
+
onFailure(exception)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
val timeoutRunnable = Runnable {
|
|
116
|
+
if (settled.compareAndSet(false, true)) {
|
|
117
|
+
Log.w(TAG, "initializeClient: PCA creation timed out after 8s — clearing cache and retrying")
|
|
118
|
+
clearMsalCache()
|
|
119
|
+
createPca(
|
|
120
|
+
onSuccess = { app ->
|
|
121
|
+
Log.d(TAG, "initializeClient: PCA onCreated after cache clear")
|
|
122
|
+
pca = app
|
|
123
|
+
promise.resolve(null)
|
|
124
|
+
},
|
|
125
|
+
onFailure = { ex ->
|
|
126
|
+
Log.e(TAG, "initializeClient: PCA onError after cache clear: ${ex.message}")
|
|
127
|
+
promise.reject("E_MSAL_INIT", ex.message, ex)
|
|
128
|
+
}
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
mainHandler.postDelayed(timeoutRunnable, 8_000L)
|
|
133
|
+
|
|
134
|
+
createPca(
|
|
135
|
+
onSuccess = { app ->
|
|
136
|
+
if (settled.compareAndSet(false, true)) {
|
|
137
|
+
mainHandler.removeCallbacks(timeoutRunnable)
|
|
138
|
+
pca = app
|
|
139
|
+
promise.resolve(null)
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
onFailure = { ex ->
|
|
143
|
+
if (settled.compareAndSet(false, true)) {
|
|
144
|
+
mainHandler.removeCallbacks(timeoutRunnable)
|
|
145
|
+
promise.reject("E_MSAL_INIT", ex.message, ex)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// -------------------------------------------------------------------------
|
|
152
|
+
// acquireTokenInteractive
|
|
153
|
+
// -------------------------------------------------------------------------
|
|
154
|
+
AsyncFunction("acquireTokenInteractive") {
|
|
155
|
+
scopes: List<String>,
|
|
156
|
+
loginHint: String?,
|
|
157
|
+
prompt: String?,
|
|
158
|
+
promise: Promise ->
|
|
159
|
+
|
|
160
|
+
val client = pca
|
|
161
|
+
?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
|
|
162
|
+
val activity = appContext.activityProvider?.currentActivity
|
|
163
|
+
?: return@AsyncFunction promise.reject("E_NO_ACTIVITY", "No activity available", null)
|
|
164
|
+
|
|
165
|
+
val params = AcquireTokenParameters.Builder()
|
|
166
|
+
.startAuthorizationFromActivity(activity)
|
|
167
|
+
.withScopes(scopes)
|
|
168
|
+
.apply {
|
|
169
|
+
loginHint?.let { withLoginHint(it) }
|
|
170
|
+
prompt?.let { withPrompt(mapPrompt(it)) }
|
|
171
|
+
}
|
|
172
|
+
.withCallback(object : AuthenticationCallback {
|
|
173
|
+
override fun onSuccess(result: IAuthenticationResult) {
|
|
174
|
+
promise.resolve(serializeResult(result))
|
|
175
|
+
}
|
|
176
|
+
override fun onError(exception: MsalException) {
|
|
177
|
+
promise.reject("E_MSAL_INTERACTIVE", exception.message, exception)
|
|
178
|
+
}
|
|
179
|
+
override fun onCancel() {
|
|
180
|
+
promise.reject("E_MSAL_CANCELLED", "User cancelled sign-in", null)
|
|
181
|
+
}
|
|
182
|
+
})
|
|
183
|
+
.build()
|
|
184
|
+
|
|
185
|
+
client.acquireToken(params)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// -------------------------------------------------------------------------
|
|
189
|
+
// acquireTokenSilent
|
|
190
|
+
// -------------------------------------------------------------------------
|
|
191
|
+
AsyncFunction("acquireTokenSilent") {
|
|
192
|
+
scopes: List<String>,
|
|
193
|
+
accountIdentifier: String,
|
|
194
|
+
forceRefresh: Boolean,
|
|
195
|
+
promise: Promise ->
|
|
196
|
+
|
|
197
|
+
val client = pca
|
|
198
|
+
?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
|
|
199
|
+
|
|
200
|
+
val account = findAccount(client, accountIdentifier)
|
|
201
|
+
?: return@AsyncFunction promise.reject(
|
|
202
|
+
"E_ACCOUNT_NOT_FOUND",
|
|
203
|
+
"Account '$accountIdentifier' not found in MSAL cache",
|
|
204
|
+
null
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
val params = AcquireTokenSilentParameters.Builder()
|
|
208
|
+
.withScopes(scopes)
|
|
209
|
+
.forAccount(account)
|
|
210
|
+
.fromAuthority(account.authority)
|
|
211
|
+
.forceRefresh(forceRefresh)
|
|
212
|
+
.withCallback(object : SilentAuthenticationCallback {
|
|
213
|
+
override fun onSuccess(result: IAuthenticationResult) {
|
|
214
|
+
promise.resolve(serializeResult(result))
|
|
215
|
+
}
|
|
216
|
+
override fun onError(exception: MsalException) {
|
|
217
|
+
if (exception is MsalUiRequiredException) {
|
|
218
|
+
promise.reject("E_INTERACTION_REQUIRED", exception.message, exception)
|
|
219
|
+
} else {
|
|
220
|
+
promise.reject("E_MSAL_SILENT", exception.message, exception)
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
})
|
|
224
|
+
.build()
|
|
225
|
+
|
|
226
|
+
client.acquireTokenSilentAsync(params)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// -------------------------------------------------------------------------
|
|
230
|
+
// getAccounts
|
|
231
|
+
// -------------------------------------------------------------------------
|
|
232
|
+
AsyncFunction("getAccounts") { promise: Promise ->
|
|
233
|
+
val client = pca
|
|
234
|
+
?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
|
|
235
|
+
|
|
236
|
+
// Use synchronous client.accounts instead of the async LoadAccountsCallback.
|
|
237
|
+
// The async callback deadlocks under Bridgeless/New Architecture: it dispatches
|
|
238
|
+
// back onto a thread the expo-modules coroutine dispatcher already holds, so it
|
|
239
|
+
// never fires and the JS promise hangs (isLoading stays true forever).
|
|
240
|
+
// AsyncFunction runs on a background thread so blocking here is safe.
|
|
241
|
+
try {
|
|
242
|
+
val accounts = client.accounts
|
|
243
|
+
Log.d(TAG, "getAccounts: found ${accounts.size} account(s)")
|
|
244
|
+
promise.resolve(accounts.map { serializeAccount(it) })
|
|
245
|
+
} catch (e: MsalException) {
|
|
246
|
+
Log.e(TAG, "getAccounts: MsalException: ${e.message}")
|
|
247
|
+
promise.reject("E_MSAL_ACCOUNTS", e.message, e)
|
|
248
|
+
} catch (e: InterruptedException) {
|
|
249
|
+
Log.e(TAG, "getAccounts: interrupted")
|
|
250
|
+
promise.reject("E_MSAL_ACCOUNTS", "Interrupted while loading accounts", e)
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// -------------------------------------------------------------------------
|
|
255
|
+
// signOut
|
|
256
|
+
// -------------------------------------------------------------------------
|
|
257
|
+
AsyncFunction("signOut") {
|
|
258
|
+
accountIdentifier: String,
|
|
259
|
+
signoutFromBrowser: Boolean,
|
|
260
|
+
promise: Promise ->
|
|
261
|
+
|
|
262
|
+
val client = pca
|
|
263
|
+
?: return@AsyncFunction promise.reject("E_NOT_INIT", notInitMsg, null)
|
|
264
|
+
val account = findAccount(client, accountIdentifier)
|
|
265
|
+
?: return@AsyncFunction promise.reject(
|
|
266
|
+
"E_ACCOUNT_NOT_FOUND",
|
|
267
|
+
"Account '$accountIdentifier' not found in MSAL cache",
|
|
268
|
+
null
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
// Use synchronous removeAccount overload — same reason as getAccounts:
|
|
272
|
+
// the async RemoveAccountCallback deadlocks under Bridgeless, leaving
|
|
273
|
+
// isLoading=true after signout so the loading spinner never clears.
|
|
274
|
+
try {
|
|
275
|
+
Log.d(TAG, "signOut: removing account ${account.id}")
|
|
276
|
+
client.removeAccount(account)
|
|
277
|
+
Log.d(TAG, "signOut: account removed successfully")
|
|
278
|
+
promise.resolve(null)
|
|
279
|
+
} catch (e: MsalException) {
|
|
280
|
+
Log.e(TAG, "signOut: MsalException: ${e.message}")
|
|
281
|
+
promise.reject("E_MSAL_SIGNOUT", e.message, e)
|
|
282
|
+
} catch (e: InterruptedException) {
|
|
283
|
+
Log.e(TAG, "signOut: interrupted")
|
|
284
|
+
promise.reject("E_MSAL_SIGNOUT", "Interrupted during sign-out", e)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// -------------------------------------------------------------------------
|
|
289
|
+
// Intune: registerAndEnrollAccount
|
|
290
|
+
// -------------------------------------------------------------------------
|
|
291
|
+
AsyncFunction("registerAndEnrollAccount") {
|
|
292
|
+
upn: String,
|
|
293
|
+
aadId: String,
|
|
294
|
+
tenantId: String,
|
|
295
|
+
promise: Promise ->
|
|
296
|
+
|
|
297
|
+
try {
|
|
298
|
+
val mamComponentsClass = Class.forName("com.microsoft.intune.mam.client.app.MAMComponents")
|
|
299
|
+
val mamEnrollmentManagerClass = Class.forName("com.microsoft.intune.mam.policy.MAMEnrollmentManager")
|
|
300
|
+
val enrollmentManager = mamComponentsClass.getMethod("get", Class::class.java)
|
|
301
|
+
.invoke(null, mamEnrollmentManagerClass)
|
|
302
|
+
?: throw IllegalStateException("MAMEnrollmentManager is null — ensure the app extends MAMApplication")
|
|
303
|
+
mamEnrollmentManagerClass.getMethod("registerAccountForMAM", String::class.java, String::class.java, String::class.java)
|
|
304
|
+
.invoke(enrollmentManager, upn, aadId, tenantId)
|
|
305
|
+
promise.resolve(null)
|
|
306
|
+
} catch (e: ClassNotFoundException) {
|
|
307
|
+
promise.reject("E_INTUNE_UNAVAILABLE", "Intune SDK not available in this build", e)
|
|
308
|
+
} catch (e: Exception) {
|
|
309
|
+
promise.reject("E_INTUNE_ENROLL", e.message, e)
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// -------------------------------------------------------------------------
|
|
314
|
+
// Intune: deRegisterAndUnenrollAccount
|
|
315
|
+
// -------------------------------------------------------------------------
|
|
316
|
+
AsyncFunction("deRegisterAndUnenrollAccount") { upn: String, promise: Promise ->
|
|
317
|
+
try {
|
|
318
|
+
val mamComponentsClass = Class.forName("com.microsoft.intune.mam.client.app.MAMComponents")
|
|
319
|
+
val mamEnrollmentManagerClass = Class.forName("com.microsoft.intune.mam.policy.MAMEnrollmentManager")
|
|
320
|
+
val enrollmentManager = mamComponentsClass.getMethod("get", Class::class.java)
|
|
321
|
+
.invoke(null, mamEnrollmentManagerClass)
|
|
322
|
+
?: throw IllegalStateException("MAMEnrollmentManager is null — ensure the app extends MAMApplication")
|
|
323
|
+
mamEnrollmentManagerClass.getMethod("unregisterAccountForMAM", String::class.java)
|
|
324
|
+
.invoke(enrollmentManager, upn)
|
|
325
|
+
promise.resolve(null)
|
|
326
|
+
} catch (e: ClassNotFoundException) {
|
|
327
|
+
promise.reject("E_INTUNE_UNAVAILABLE", "Intune SDK not available in this build", e)
|
|
328
|
+
} catch (e: Exception) {
|
|
329
|
+
promise.reject("E_INTUNE_UNENROLL", e.message, e)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// -------------------------------------------------------------------------
|
|
334
|
+
// getWrapConfig — synchronous.
|
|
335
|
+
// Reads pipeline-patchable string resources at runtime so the app never
|
|
336
|
+
// has to use HBC-baked auth values in production. The production AAB+protoc
|
|
337
|
+
// pipeline (OptimizedWrapBuild.ps1) replaces these strings in resources.pb
|
|
338
|
+
// before the AAB is distributed; getWrapConfig() surfaces those patched
|
|
339
|
+
// values to JS, overriding the placeholder values baked into the HBC bundle.
|
|
340
|
+
//
|
|
341
|
+
// Caller (AuthContext) only uses these values in release builds (!__DEV__).
|
|
342
|
+
// Dev client builds continue to use auth.config.json directly.
|
|
343
|
+
// -------------------------------------------------------------------------
|
|
344
|
+
Function("getWrapConfig") {
|
|
345
|
+
val appCtx = appContext.reactContext?.applicationContext
|
|
346
|
+
?: throw IllegalStateException("getWrapConfig: no application context")
|
|
347
|
+
val res = appCtx.resources
|
|
348
|
+
val pkg = appCtx.packageName
|
|
349
|
+
|
|
350
|
+
fun str(name: String): String {
|
|
351
|
+
val id = res.getIdentifier(name, "string", pkg)
|
|
352
|
+
return if (id != 0) res.getString(id) else ""
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
mapOf(
|
|
356
|
+
"clientId" to str("adal_client_id"),
|
|
357
|
+
"redirectUri" to str("adal_redirect_uri"),
|
|
358
|
+
"tenantId" to str("adal_tenant_id"),
|
|
359
|
+
)
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// -------------------------------------------------------------------------
|
|
363
|
+
// computeMsalRedirectUri — synchronous, no Promise needed.
|
|
364
|
+
// Computes msauth://<packageName>/<base64-sha1-cert-hash> at runtime from
|
|
365
|
+
// the app's own package name and signing certificate. This means the
|
|
366
|
+
// redirect URI never has to be baked into the JS bundle (HBC), avoiding
|
|
367
|
+
// the byte-length mismatch that corrupts Hermes bytecode when the wrap
|
|
368
|
+
// script patches a fixed-length placeholder.
|
|
369
|
+
// -------------------------------------------------------------------------
|
|
370
|
+
Function("computeMsalRedirectUri") {
|
|
371
|
+
val appCtx = appContext.reactContext?.applicationContext
|
|
372
|
+
?: throw IllegalStateException("computeMsalRedirectUri: no application context")
|
|
373
|
+
val packageName = appCtx.packageName
|
|
374
|
+
|
|
375
|
+
val signingInfo = appCtx.packageManager
|
|
376
|
+
.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)
|
|
377
|
+
.signingInfo
|
|
378
|
+
?: throw IllegalStateException("computeMsalRedirectUri: signingInfo is null")
|
|
379
|
+
val signers = signingInfo.apkContentsSigners
|
|
380
|
+
?: throw IllegalStateException("computeMsalRedirectUri: apkContentsSigners is null")
|
|
381
|
+
val sigBytes: ByteArray = signers[0].toByteArray()
|
|
382
|
+
|
|
383
|
+
val sha1 = MessageDigest.getInstance("SHA-1").digest(sigBytes)
|
|
384
|
+
val hash = Base64.encodeToString(sha1, Base64.NO_WRAP)
|
|
385
|
+
// Fully URL-encode the base64 hash. MSAL Android SDK's internal redirect-URI
|
|
386
|
+
// validator generates the canonical form by encoding '+', '/', '=' (all reserved
|
|
387
|
+
// in URI path components per RFC 3986). Encoding only '=' produces an asymmetric
|
|
388
|
+
// form (e.g. 'abc/def%3D') that MSAL rejects with "redirect URI in the
|
|
389
|
+
// configuration file doesn't match with the one generated with package name and
|
|
390
|
+
// signature hash. Expected msauth://.../<fully-encoded>, received
|
|
391
|
+
// msauth://.../<partially-encoded>".
|
|
392
|
+
val encoded = hash
|
|
393
|
+
.replace("+", "%2B")
|
|
394
|
+
.replace("/", "%2F")
|
|
395
|
+
.replace("=", "%3D")
|
|
396
|
+
"msauth://$packageName/$encoded"
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ---------------------------------------------------------------------------
|
|
401
|
+
// Helpers
|
|
402
|
+
// ---------------------------------------------------------------------------
|
|
403
|
+
|
|
404
|
+
private val notInitMsg = "ExpoMsalIntune: call initializeClient() before acquiring tokens"
|
|
405
|
+
|
|
406
|
+
private fun findAccount(
|
|
407
|
+
client: IMultipleAccountPublicClientApplication,
|
|
408
|
+
identifier: String
|
|
409
|
+
): IAccount? {
|
|
410
|
+
return try {
|
|
411
|
+
client.accounts.firstOrNull { it.id == identifier }
|
|
412
|
+
} catch (e: Exception) {
|
|
413
|
+
Log.w(TAG, "getAccounts() threw: ${e.message}")
|
|
414
|
+
null
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
private fun serializeAccount(account: IAccount): Map<String, Any> {
|
|
419
|
+
val claims = try {
|
|
420
|
+
val claimsMap = account.claims ?: emptyMap<String, Any>()
|
|
421
|
+
JSONObject(claimsMap).toString()
|
|
422
|
+
} catch (e: Exception) {
|
|
423
|
+
"{}"
|
|
424
|
+
}
|
|
425
|
+
return mapOf(
|
|
426
|
+
"identifier" to (account.id ?: ""),
|
|
427
|
+
"username" to (account.username ?: ""),
|
|
428
|
+
"tenantId" to (account.tenantId ?: ""),
|
|
429
|
+
"claims" to claims,
|
|
430
|
+
)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private fun serializeResult(result: IAuthenticationResult): Map<String, Any> {
|
|
434
|
+
return mapOf(
|
|
435
|
+
"accessToken" to result.accessToken,
|
|
436
|
+
// IAuthenticationResult in MSAL 5.x does not expose getIdToken() directly.
|
|
437
|
+
// The raw ID token is accessible via IAccount (which extends IClaimable).
|
|
438
|
+
"idToken" to (result.account.idToken ?: ""),
|
|
439
|
+
"expiresOn" to result.expiresOn.time,
|
|
440
|
+
"scopes" to result.scope.toList(),
|
|
441
|
+
"account" to serializeAccount(result.account),
|
|
442
|
+
)
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
private fun mapPrompt(prompt: String): Prompt = when (prompt) {
|
|
446
|
+
"login" -> Prompt.LOGIN
|
|
447
|
+
"consent" -> Prompt.CONSENT
|
|
448
|
+
"select_account" -> Prompt.SELECT_ACCOUNT
|
|
449
|
+
"none" -> Prompt.WHEN_REQUIRED
|
|
450
|
+
else -> Prompt.WHEN_REQUIRED
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Builds the MSAL config JSON object.
|
|
455
|
+
*
|
|
456
|
+
* useEmbeddedWebView=true → WEBVIEW mode: MSAL uses an embedded WebView Activity
|
|
457
|
+
* and intercepts the nativeclient redirect URI. No BrowserTabActivity or
|
|
458
|
+
* intent-filter required in AndroidManifest — safe to change at JS runtime.
|
|
459
|
+
*
|
|
460
|
+
* useEmbeddedWebView=false, useBroker=false → DEFAULT (Custom Tab).
|
|
461
|
+
* useEmbeddedWebView=false, useBroker=true → DEFAULT + broker enabled.
|
|
462
|
+
* Requires BrowserTabActivity in AndroidManifest (added by wrap pipeline).
|
|
463
|
+
*/
|
|
464
|
+
private fun buildMsalConfigJson(
|
|
465
|
+
clientId: String,
|
|
466
|
+
authority: String,
|
|
467
|
+
redirectUri: String,
|
|
468
|
+
useEmbeddedWebView: Boolean,
|
|
469
|
+
useBroker: Boolean,
|
|
470
|
+
): JSONObject {
|
|
471
|
+
return JSONObject().apply {
|
|
472
|
+
put("client_id", clientId)
|
|
473
|
+
put("redirect_uri", redirectUri)
|
|
474
|
+
// useEmbeddedWebView=true → WEBVIEW: no BrowserTabActivity/broker needed.
|
|
475
|
+
// useBroker=true → DEFAULT + broker_redirect_uri_registered: true.
|
|
476
|
+
// else → DEFAULT (Custom Tab), no broker.
|
|
477
|
+
put("authorization_user_agent", if (useEmbeddedWebView) "WEBVIEW" else "DEFAULT")
|
|
478
|
+
put("broker_redirect_uri_registered", useBroker)
|
|
479
|
+
put("authorities", JSONArray().apply {
|
|
480
|
+
put(JSONObject().apply {
|
|
481
|
+
put("type", "AAD")
|
|
482
|
+
put("authority_url", authority)
|
|
483
|
+
put("default", true)
|
|
484
|
+
})
|
|
485
|
+
})
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
package/app.plugin.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Pod::Spec.new do |s|
|
|
2
|
+
s.name = 'ExpoMsalIntune'
|
|
3
|
+
s.version = '0.1.0'
|
|
4
|
+
s.summary = 'Expo module: MSAL + Intune MAM for iOS'
|
|
5
|
+
s.description = 'Wraps the Microsoft Authentication Library (MSAL) and the ' \
|
|
6
|
+
'Microsoft Intune App SDK as an Expo native module.'
|
|
7
|
+
s.author = 'Microsoft'
|
|
8
|
+
s.homepage = 'https://github.com/microsoft/pa-wrap-tools'
|
|
9
|
+
s.license = { :type => 'MIT' }
|
|
10
|
+
s.platforms = { :ios => '14.0' }
|
|
11
|
+
s.source = { :path => '.' }
|
|
12
|
+
s.static_framework = true
|
|
13
|
+
|
|
14
|
+
s.dependency 'ExpoModulesCore'
|
|
15
|
+
# MSAL iOS — latest: 2.10.0
|
|
16
|
+
s.dependency 'MSAL', '~> 2.10'
|
|
17
|
+
|
|
18
|
+
# IntuneMAMSwift iOS 20.9.2 (Xcode 16 compatible; 21.x requires Xcode 26)
|
|
19
|
+
# Vendored locally because IntuneMAMSwift is not published to the public CocoaPods CDN.
|
|
20
|
+
# To upgrade: download the new release from
|
|
21
|
+
# https://github.com/microsoftconnect/ms-intune-app-sdk-ios/releases
|
|
22
|
+
# and replace the contents of ios/Frameworks/.
|
|
23
|
+
s.vendored_frameworks = 'Frameworks/IntuneMAMSwift.xcframework',
|
|
24
|
+
'Frameworks/IntuneMAMSwiftStub.xcframework'
|
|
25
|
+
|
|
26
|
+
s.source_files = '*.{swift,h,m}'
|
|
27
|
+
end
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import ExpoModulesCore
|
|
2
|
+
import MSAL
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ExpoAppDelegateSubscriber that forwards incoming URLs to MSAL.
|
|
6
|
+
*
|
|
7
|
+
* When broker auth is enabled (`useBroker: true`) the Microsoft Authenticator
|
|
8
|
+
* or Company Portal app redirects back to this app via the
|
|
9
|
+
* `msauth.<bundleId>://auth` URL scheme. MSAL must intercept that URL at the
|
|
10
|
+
* AppDelegate level; this subscriber handles that without requiring any
|
|
11
|
+
* AppDelegate modifications.
|
|
12
|
+
*
|
|
13
|
+
* expo-modules-core autolinking discovers classes conforming to
|
|
14
|
+
* `ExpoAppDelegateSubscriber` automatically — no manual registration needed.
|
|
15
|
+
*/
|
|
16
|
+
public class ExpoMsalIntuneAppDelegate: ExpoAppDelegateSubscriber {
|
|
17
|
+
|
|
18
|
+
public func application(
|
|
19
|
+
_ app: UIApplication,
|
|
20
|
+
open url: URL,
|
|
21
|
+
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
|
|
22
|
+
) -> Bool {
|
|
23
|
+
// Let MSAL inspect the URL. Returns true when MSAL handled it (i.e. it
|
|
24
|
+
// was a broker redirect). Returns false for all other URLs so they
|
|
25
|
+
// continue down the responder chain to expo-linking etc.
|
|
26
|
+
return MSALPublicClientApplication.handleMSALResponse(
|
|
27
|
+
url,
|
|
28
|
+
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
}
|