Skip to content

Commit 8123bc6

Browse files
authored
Merge pull request #106967 from jmprieur/master
Adding support for Android broker
2 parents 403a99b + da078ad commit 8123bc6

File tree

1 file changed

+119
-16
lines changed

1 file changed

+119
-16
lines changed

articles/active-directory/develop/msal-net-use-brokers-with-xamarin-apps.md

Lines changed: 119 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,12 @@ public override bool OpenUrl(UIApplication app, NSUrl url,
7272
}
7373

7474
else if (!AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(url))
75-
{
76-
return false;
75+
{
76+
return false;
7777
}
78-
79-
return true;
80-
}
78+
79+
return true;
80+
}
8181
```
8282

8383
This method is invoked every time the application is started. It's used as an opportunity to process the response from the broker and complete the authentication process that MSAL.NET started.
@@ -93,28 +93,28 @@ To set up the object window:
9393
1. On the `AcquireTokenInteractive` call, use `.WithParentActivityOrWindow(App.RootViewController)` and then pass in the reference to the object window you'll use.
9494

9595
In `App.cs`:
96-
96+
9797
```csharp
9898
public static object RootViewController { get; set; }
9999
```
100-
100+
101101
In `AppDelegate.cs`:
102-
102+
103103
```csharp
104104
LoadApplication(new App());
105105
App.RootViewController = new UIViewController();
106106
```
107-
107+
108108
In the `AcquireToken` call:
109-
109+
110110
```csharp
111111
result = await app.AcquireTokenInteractive(scopes)
112112
.WithParentActivityOrWindow(App.RootViewController)
113113
.ExecuteAsync();
114114
```
115115

116116
### Step 5: Register a URL scheme
117-
MSAL.NET uses URLs to invoke the broker and then return the broker response to your app. To finish the round trip, register a URL scheme for your app in the `Info.plist` file.
117+
MSAL.NET uses URLs to invoke the broker and then return the broker response to your app. To complete the round trip, register a URL scheme for your app in the `Info.plist` file.
118118

119119
The `CFBundleURLSchemes` name must include `msauth.` as a prefix. Follow the prefix with `CFBundleURLName`.
120120

@@ -140,11 +140,12 @@ In the URL scheme, `BundleId` uniquely identifies the app: `$"msauth.(BundleId)"
140140
```
141141

142142
### Step 6: Add the broker identifier to the LSApplicationQueriesSchemes section
143+
143144
MSAL uses `–canOpenURL:` to check whether the broker is installed on the device. In iOS 9, Apple locked down the schemes that an application can query for.
144145

145146
Add `msauthv2` to the `LSApplicationQueriesSchemes` section of the `Info.plist` file, as in the following example:
146147

147-
```XML
148+
```XML
148149
<key>LSApplicationQueriesSchemes</key>
149150
<array>
150151
<string>msauthv2</string>
@@ -153,16 +154,19 @@ Add `msauthv2` to the `LSApplicationQueriesSchemes` section of the `Info.plist`
153154
```
154155

155156
### Step 7: Register your redirect URI in the application portal
157+
156158
When you use the broker, your redirect URI has an extra requirement. The redirect URI _must_ have the following format:
159+
157160
```csharp
158161
$"msauth.{BundleId}://auth"
159162
```
160163

161-
Here's an example:
164+
Here's an example:
162165

163166
```csharp
164167
public static string redirectUriOnIos = "msauth.com.yourcompany.XForms://auth";
165168
```
169+
166170
Notice that the redirect URI matches the `CFBundleURLSchemes` name that you included in the `Info.plist` file.
167171

168172
### Step 8: Make sure the redirect URI is registered with your app
@@ -189,15 +193,114 @@ To compute the redirect URI:
189193

190194
![Enter the bundle ID](media/msal-net-use-brokers-with-xamarin-apps/60799477-7eaba580-a173-11e9-9f8b-431f5b09344e.png)
191195

192-
When you finish the steps, the redirect URI is computed for you.
196+
When you're done with the steps, the redirect URI is computed for you.
193197

194198
![Copy redirect URI](media/msal-net-use-brokers-with-xamarin-apps/60799538-9e42ce00-a173-11e9-860a-015a1840fd19.png)
195199

196200
## Brokered authentication for Android
197201

198-
MSAL.NET supports only the Xamarin.iOS platform. It doesn't yet support brokers for the Xamarin.Android platform.
202+
### Step 1: Enable broker support
203+
204+
Broker support is enabled on a per-PublicClientApplication basis. It's disabled by default. Use the `WithBroker()` parameter (set to true by default) when creating the `IPublicClientApplication` through the `PublicClientApplicationBuilder`.
205+
206+
```CSharp
207+
var app = PublicClientApplicationBuilder
208+
.Create(ClientId)
209+
.WithBroker()
210+
.WithRedirectUri(redirectUriOnAndroid) //(see step 4 below)
211+
.Build();
212+
```
213+
214+
### Step 2: Update AppDelegate to handle the callback
215+
216+
When MSAL.NET calls the broker, the broker will, in turn, call back to your application with the OnActivityResult() method. Since MSAL will wait for the response from the broker, your application needs to route the result to MSAL.NET.
217+
This can be achieved by routing the result to the `SetAuthenticationContinuationEventArgs(int requestCode, Result resultCode, Intent data)` by overriding the OnActivityResult() method as shown below
218+
219+
```CSharp
220+
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
221+
{
222+
base.OnActivityResult(requestCode, resultCode, data);
223+
AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(requestCode, resultCode, data);
224+
}
225+
```
226+
227+
This method is invoked every time the broker application is launched and is used as an opportunity to process the response from the broker and complete the authentication process started by MSAL.NET.
228+
229+
### Step 3: Set an Activity
230+
231+
For brokered authentication to work you'll need to set an activity so that MSAL can send and receive the response from broker.
232+
233+
To do this, you'll need to provide the activity(usually the MainActivity) to the `WithParentActivityOrWindow(object parent)` as the parent object.
234+
235+
**For example:**
236+
237+
In the Acquire Token call:
238+
239+
```CSharp
240+
result = await app.AcquireTokenInteractive(scopes)
241+
.WithParentActivityOrWindow((Activity)context))
242+
.ExecuteAsync();
243+
```
244+
245+
### Step 4: Register your RedirectUri in the application portal
246+
247+
MSAL uses URLs to invoke the broker and then return back to your app. To complete that round trip, you need to register a URL scheme for your app. This Redirect URI needs to be registered on the Azure AD app registration portal as a valid redirect URI for your application.
248+
249+
250+
The redirect URI needed for your application is dependent on the certificate used to sign the APK.
251+
252+
```
253+
Example: msauth://com.microsoft.xforms.testApp/hgbUYHVBYUTvuvT&Y6tr554365466=
254+
```
255+
256+
The last part of the URI, `hgbUYHVBYUTvuvT&Y6tr554365466=`, is the signature that the APK is signed with, base64 encoded.
257+
However, during the development phase of your application using Visual Studio, if you're debugging your code without signing the apk with a specific certificate, Visual Studio will sign the apk for you for debugging purposes, giving the APK a unique signature for the machine that it's built on. Thus, each time you build your app on a different machine, you'll need to update the redirect URI in the application's code and the application's registration in the Azure portal in order to authenticate with MSAL.
258+
259+
While debugging, you may encounter an MSAL exception (or log message) stating the redirect URI provided is incorrect. **This exception will also provide you with the redirect URI that you should be using** with the current machine you are debugging on. You can use this redirect URI to continue developing for the time being.
260+
261+
Once you are ready to finalize your code, be sure to update the redirect URI in the code and on the application's registration in the Azure portal to use the signature of the certificate you will be signing the APK with.
262+
263+
In practice, this means that you have to register a redirect URI for each member of the team, plus a redirect URI for the production signed version of the APK.
264+
265+
You can also compute this signature yourself, similar to how MSAL does it:
266+
267+
```CSharp
268+
private string GetRedirectUriForBroker()
269+
{
270+
string packageName = Application.Context.PackageName;
271+
string signatureDigest = this.GetCurrentSignatureForPackage(packageName);
272+
if (!string.IsNullOrEmpty(signatureDigest))
273+
{
274+
return string.Format(CultureInfo.InvariantCulture, "{0}://{1}/{2}", RedirectUriScheme,
275+
packageName.ToLowerInvariant(), signatureDigest);
276+
}
277+
278+
return string.Empty;
279+
}
280+
281+
private string GetCurrentSignatureForPackage(string packageName)
282+
{
283+
PackageInfo info = Application.Context.PackageManager.GetPackageInfo(packageName,
284+
PackageInfoFlags.Signatures);
285+
if (info != null && info.Signatures != null && info.Signatures.Count > 0)
286+
{
287+
// First available signature. Applications can be signed with multiple signatures.
288+
// The order of Signatures is not guaranteed.
289+
Signature signature = info.Signatures[0];
290+
MessageDigest md = MessageDigest.GetInstance("SHA");
291+
md.Update(signature.ToByteArray());
292+
return Convert.ToBase64String(md.Digest(), Base64FormattingOptions.None);
293+
// Server side needs to register all other tags. ADAL will
294+
// send one of them.
295+
}
296+
}
297+
```
298+
299+
You also have the option of acquiring the signature for your package by using the keytool with the following commands:
300+
301+
For Windows: `keytool.exe -list -v -keystore "%LocalAppData%\Xamarin\Mono for Android\debug.keystore" -alias androiddebugkey -storepass android -keypass android`
199302

200-
The MSAL Android native library already supports brokered authentication. For more information, see [Brokered authentication in Android](brokered-auth.md).
303+
For Mac: `keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64`
201304

202305
## Next steps
203306

0 commit comments

Comments
 (0)