Skip to content
This repository was archived by the owner on Jun 10, 2025. It is now read-only.

Commit 473303d

Browse files
authored
Merge pull request #17 from Azure-Samples/oldalton/update_to_latest_msal
Updated B2C sample to latest MSAL and updated readme.md
2 parents 660e0e8 + ecb1322 commit 473303d

File tree

5 files changed

+74
-46
lines changed

5 files changed

+74
-46
lines changed

Cartfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
github "AzureAD/microsoft-authentication-library-for-objc" "0.4.2"
1+
github "AzureAD/microsoft-authentication-library-for-objc" "master"

Cartfile.resolved

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
github "AzureAD/microsoft-authentication-library-for-objc" "c0aaed2a1763907a9b1fca6fc8aa5c2995a07bd3"

MSALiOSB2C/Base.lproj/Main.storyboard

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12120" systemVersion="16E195" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
3-
<device id="retina4_7" orientation="portrait">
4-
<adaptation id="fullscreen"/>
5-
</device>
2+
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14865.1" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
3+
<device id="retina4_7" orientation="portrait" appearance="light"/>
64
<dependencies>
75
<deployment identifier="iOS"/>
8-
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
6+
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14819.2"/>
97
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
108
</dependencies>
119
<scenes>
@@ -70,7 +68,7 @@
7068
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
7169
<state key="normal" title="Call API"/>
7270
<connections>
73-
<action selector="callApi:" destination="BYZ-38-t0r" eventType="touchUpInside" id="4VR-5A-u4F"/>
71+
<action selector="callApi:" destination="BYZ-38-t0r" eventType="touchUpInside" id="cE2-ql-o7T"/>
7472
</connections>
7573
</button>
7674
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="GAR-kV-sCk">

MSALiOSB2C/ViewController.swift

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,11 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
6666
The scheme part, i.e. "msal<your-client-id-here>", needs to be registered in the info.plist of the project
6767
*/
6868

69-
let pcaConfig = MSALPublicClientApplicationConfig(clientId: kClientID)
69+
let authority = try self.getAuthority(forPolicy: self.kSignupOrSigninPolicy)
70+
71+
// Provide configuration for MSALPublicClientApplication
72+
// MSAL will use default redirect uri when you provide nil
73+
let pcaConfig = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: nil, authority: authority)
7074
self.application = try MSALPublicClientApplication(configuration: pcaConfig)
7175
} catch {
7276
self.updateLoggingText(text: "Unable to create application \(error)")
@@ -104,19 +108,23 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
104108
flow completes, or encounters an error.
105109
*/
106110

107-
let parameters = MSALInteractiveTokenParameters(scopes: kScopes)
111+
let webViewParameters = MSALWebviewParameters(parentViewController: self)
112+
let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: webViewParameters)
113+
parameters.promptType = .selectAccount
108114
parameters.authority = authority
109115
application.acquireToken(with: parameters) { (result, error) in
110-
if let result = result {
111-
self.accessToken = result.accessToken
112-
self.updateLoggingText(text: "Access token is \(self.accessToken ?? "Empty")")
113-
self.signoutButton.isEnabled = true
114-
self.callGraphApiButton.isEnabled = true
115-
self.editProfileButton.isEnabled = true
116-
self.refreshTokenButton.isEnabled = true
117-
} else {
116+
117+
guard let result = result else {
118118
self.updateLoggingText(text: "Could not acquire token: \(error ?? "No error informarion" as! Error)")
119+
return
119120
}
121+
122+
self.accessToken = result.accessToken
123+
self.updateLoggingText(text: "Access token is \(self.accessToken ?? "Empty")")
124+
self.signoutButton.isEnabled = true
125+
self.callGraphApiButton.isEnabled = true
126+
self.editProfileButton.isEnabled = true
127+
self.refreshTokenButton.isEnabled = true
120128
}
121129
} catch {
122130
self.updateLoggingText(text: "Unable to create authority \(error)")
@@ -150,7 +158,8 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
150158
*/
151159

152160
let thisAccount = try self.getAccountByPolicy(withAccounts: application.allAccounts(), policy: kEditProfilePolicy)
153-
let parameters = MSALInteractiveTokenParameters(scopes: kScopes)
161+
let webViewParameters = MSALWebviewParameters(parentViewController: self)
162+
let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: webViewParameters)
154163
parameters.authority = authority
155164
parameters.account = thisAccount
156165

@@ -167,6 +176,7 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
167176
}
168177

169178
@IBAction func refreshToken(_ sender: UIButton) {
179+
170180
do {
171181
/**
172182

@@ -217,17 +227,19 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
217227
// Notice we supply the account here. This ensures we acquire token for the same account
218228
// as we originally authenticated.
219229

220-
let parameters = MSALInteractiveTokenParameters(scopes: self.kScopes)
230+
let webviewParameters = MSALWebviewParameters(parentViewController: self)
231+
let parameters = MSALInteractiveTokenParameters(scopes: self.kScopes, webviewParameters: webviewParameters)
221232
parameters.account = thisAccount
222233

223234
self.application.acquireToken(with: parameters) { (result, error) in
224-
if let result = result {
225-
self.accessToken = result.accessToken
226-
self.updateLoggingText(text: "Access token is \(self.accessToken ?? "empty")")
227-
228-
} else {
235+
236+
guard let result = result else {
229237
self.updateLoggingText(text: "Could not acquire new token: \(error ?? "No error informarion" as! Error)")
238+
return
230239
}
240+
241+
self.accessToken = result.accessToken
242+
self.updateLoggingText(text: "Access token is \(self.accessToken ?? "empty")")
231243
}
232244
return
233245
}
@@ -259,11 +271,14 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
259271
}
260272

261273
let sessionConfig = URLSessionConfiguration.default
274+
sessionConfig.timeoutIntervalForRequest = 30
262275
let url = URL(string: self.kGraphURI)
263276
var request = URLRequest(url: url!)
264277
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
265278
let urlSession = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: OperationQueue.main)
266279

280+
self.updateLoggingText(text: "Calling the API....")
281+
267282
urlSession.dataTask(with: request) { data, response, error in
268283
guard let validData = data else {
269284
self.updateLoggingText(text: "Could not call API: \(error ?? "No error informarion" as! Error)")
@@ -302,6 +317,8 @@ class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate
302317
self.editProfileButton.isEnabled = false
303318
self.refreshTokenButton.isEnabled = false
304319

320+
self.updateLoggingText(text: "Signed out")
321+
305322
} catch {
306323
self.updateLoggingText(text: "Received error signing out: \(error)")
307324
}

README.md

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ urlFragment: microsoft-authentication-library-b2c-ios
1414
| [Getting Started](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-get-started)| [Library](https://github.com/AzureAD/microsoft-authentication-library-for-objc) | [Docs](https://aka.ms/aadb2c) | [Support](README.md#community-help-and-support)
1515
| --- | --- | --- | --- |
1616

17-
The MSAL preview library for iOS and macOS gives your app the ability to begin using the [Microsoft Cloud](https://cloud.microsoft.com) by supporting [Azure B2C](https://azure.microsoft.com/en-us/services/active-directory-b2c/) using industry standard OAuth2 and OpenID Connect. This sample demonstrates all the normal lifecycles your application should experience, including:
17+
The MSAL library for iOS and macOS gives your app the ability to begin using the [Microsoft identity platform](https://aka.ms/aaddev) by supporting [Azure B2C](https://azure.microsoft.com/en-us/services/active-directory-b2c/) using industry standard OAuth2 and OpenID Connect. This sample demonstrates all the normal lifecycles your application should experience, including:
1818

1919
* How to get a token
2020
* How to refresh a token
@@ -25,26 +25,31 @@ The MSAL preview library for iOS and macOS gives your app the ability to begin u
2525

2626
```swift
2727
do {
28-
// Create an instance of MSALPublicClientApplication with proper config
29-
let authority = try MSALB2CAuthority(url: URL(string:kAuthority)!)
30-
let pcaConfig = MSALPublicClientApplicationConfig(clientId: <your-client-id-here>, redirectUri: nil, authority: authority)
31-
let application = try MSALPublicClientApplication(configuration: pcaConfig)
32-
33-
application.acquireToken(forScopes: kScopes) { (result, error) in
34-
DispatchQueue.main.async {
35-
if result != nil {
36-
// Set up your application for the user
37-
} else {
38-
print(error)
39-
}
40-
}
41-
}
28+
// Create an instance of MSALPublicClientApplication with proper config
29+
let authority = try MSALB2CAuthority(url: URL(string: "<your-authority-here>")!)
30+
let pcaConfig = MSALPublicClientApplicationConfig(clientId: "<your-client-id-here>", redirectUri: nil, authority: authority)
31+
let application = try MSALPublicClientApplication(configuration: pcaConfig)
32+
33+
let viewController = self /*replace with your main presentation controller here */
34+
let webViewParameters = MSALWebviewParameters(parentViewController: viewController)
35+
let interactiveParameters = MSALInteractiveTokenParameters(scopes: ["<enter-your-scope-here>"], webviewParameters: webViewParameters)
36+
37+
application.acquireToken(with: interactiveParameters) { (result, error) in
38+
39+
guard let result = result else {
40+
print(error!) /* MSAL token acquisition failed, check error information */
41+
return
42+
}
43+
44+
let accessToken = result.accessToken
45+
let account = result.account
46+
/* MSAL token acquisition succeeded, use access token or check account */
47+
48+
}
49+
}
50+
catch {
51+
print(error) /* MSALPublicClientApplication creation failed, check error information */
4252
}
43-
44-
catch {
45-
print(error)
46-
}
47-
}
4853
```
4954

5055
## App Registration
@@ -60,7 +65,7 @@ We use [Carthage](https://github.com/Carthage/Carthage) for package management d
6065

6166
1. Install Carthage on your Mac using a download from their website or if using Homebrew `brew install carthage`.
6267
1. We have already created a `Cartfile` that lists the MSAL library for this project on Github. We use the `/dev` branch.
63-
1. Run `carthage bootstrap`. This will fetch dependencies into a `Carthage/Checkouts` folder, then build the MSAL library.
68+
1. Run `carthage bootstrap --platform iOS`. This will fetch dependencies into a `Carthage/Checkouts` folder, then build the MSAL library.
6469
1. On your application targets’ “General” settings tab, in the “Linked Frameworks and Libraries” section, drag and drop the `MSAL.framework` from the `Carthage/Build` folder on disk.
6570
1. On your application targets’ “Build Phases” settings tab, click the “+” icon and choose “New Run Script Phase”. Create a Run Script in which you specify your shell (ex: `/bin/sh`), add the following contents to the script area below the shell:
6671

@@ -124,9 +129,16 @@ To provide a recommendation, visit our [User Voice page](https://feedback.azure.
124129

125130
## Contribute
126131

127-
We enthusiastically welcome contributions and feedback. You can clone the repo and start contributing now. Read our [Contribution Guide](Contributing.md) for more information.
132+
We enthusiastically welcome contributions and feedback. You can clone the repo and start contributing now.
128133

129134
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
130135

136+
## Security Library
137+
138+
This library controls how users sign-in and access services. We recommend you always take the latest version of our library in your app when possible. We use [semantic versioning](http://semver.org) so you can control the risk associated with updating your app. As an example, always downloading the latest minor version number (e.g. x.*y*.x) ensures you get the latest security and feature enhanements but our API surface remains the same. You can always see the latest version and release notes under the Releases tab of GitHub.
139+
140+
## Security Reporting
141+
142+
If you find a security issue with our libraries or services please report it to [[email protected]](mailto:[email protected]) with as much detail as possible. Your submission may be eligible for a bounty through the [Microsoft Bounty](http://aka.ms/bugbounty) program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting [this page](https://technet.microsoft.com/en-us/security/dd252948) and subscribing to Security Advisory Alerts.
131143

132144
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");

0 commit comments

Comments
 (0)