Latest 0.4.3
Homepage https://github.com/AzureAD/microsoft-authentication-library-for-objc
License MIT
Platforms ios 10.0, osx 10.11
Authors

Microsoft Authentication Library Preview for iOS

Get Started Sample Code Support

The MSAL library preview gives your app the ability to begin using the Microsoft Identity platform by supporting Azure Active Directory and Microsoft Accounts in a converged experience using industry standard OAuth2 and OpenID Connect. The library also supports Azure AD B2C for those using our hosted identity management service.

Note that for the preview, only iOS is supported. macOS support will be provided in a future realse. Need it sooner? Let us know!

Important Note about the MSAL Preview

These libraries are suitable to use in a production environment. We provide the same production level support for these libraries as we do our current production libraries. During the preview we reserve the right to make changes to the API, cache format, and other mechanisms of this library without notice which you will be required to take along with bug fixes or feature improvements This may impact your application. For instance, a change to the cache format may impact your users, such as requiring them to sign in again and an API change may require you to update your code. When we provide our General Availability release later, we will require you to update your application to our General Availabilty version within six months to continue to get support.

Build Status

Swift

        let config = MSALPublicClientApplicationConfig(clientId: "<your-client-id-here>")
        let scopes = ["your-scope1-here", "your-scope2-here"]

        if let application = try? MSALPublicClientApplication(configuration: config) {

            let interactiveParameters = MSALInteractiveTokenParameters(scopes: scopes)
            application.acquireToken(with: interactiveParameters, completionBlock: { (result, error) in

                guard let authResult = result, error == nil else {
                    print(error!.localizedDescription)
                    return
                }

                // Get access token from result
                let accessToken = authResult.accessToken

                // You'll want to get the account identifier to retrieve and reuse the account for later acquireToken calls
                let accountIdentifier = authResult.account.homeAccountId?.identifier
            })
        }
        else {
            print("Unable to create application.")
        }

Objective-C

    NSError *msalError;

    MSALPublicClientApplicationConfig *config = [[MSALPublicClientApplicationConfig alloc] initWithClientId:@"<your-client-id-here>"];
    NSArray<NSString *> *scopes = @[@"your-scope1-here", @"your-scope2-here"];

    MSALPublicClientApplication *application = [[MSALPublicClientApplication alloc] initWithConfiguration:config error:&msalError];

    MSALInteractiveTokenParameters *interactiveParams = [[MSALInteractiveTokenParameters alloc] initWithScopes:scopes];
    [application acquireTokenWithParameters:interactiveParams completionBlock:^(MSALResult *result, NSError *error) {
        if (!error)
        {
            // You'll want to get the account identifier to retrieve and reuse the account
            // for later acquireToken calls
            NSString *accountIdentifier = result.account.homeAccountId.identifier;

            NSString *accessToken = result.accessToken;
        }
        else
        {
            // Check the error
        }
    }];

Installation

Using CocoaPods

You can use CocoaPods to install MSAL by adding it to your Podfile under target:

use_frameworks!

target 'your-target-here' do
    pod 'MSAL'
end

Using Carthage

You can use Carthage to install MSAL by adding it to your Cartfile:

github "AzureAD/microsoft-authentication-library-for-objc" "master"

Manually

You can also use Git Submodule or check out the latest release and use as framework in your application.

Configuring MSAL

Adding MSAL to your project

  1. Register your app in the Azure portal
  2. Add your application’s redirect URI scheme to your Info.plist file, it will be in the format of msauth.[BUNDLE_ID]
    <key>CFBundleURLTypes</key>
    <array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>msauth.[BUNDLE_ID]</string>
        </array>
    </dict>
    </array>
  3. Add LSApplicationQueriesSchemes to allow making call to Microsoft Authenticator if installed.

    <key>LSApplicationQueriesSchemes</key>
    <array>
    <string>msauth</string>
    <string>msauthv2</string>
    </array>

    See more info about configuring redirect uri for MSAL in our Wiki

  4. Add a new keychain group to your project Capabilities com.microsoft.adalcache . See more information about keychain groups for MSAL in our Wiki

MSAL

  1. To handle a callback, add the following to appDelegate:

Swift

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

        guard let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String else {
            return false
        }

        return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApplication)
    }

Objective-C

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    return [MSALPublicClientApplication handleMSALResponse:url 
                                         sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
}

Using MSAL

Creating an Application Object

Use the client ID from yout app listing when initializing your MSALPublicClientApplication object:

Swift

let config = MSALPublicClientApplicationConfig(clientId: "<your-client-id-here>")
let application = try? MSALPublicClientApplication(configuration: config) 

Objective-C

NSError *msalError;

MSALPublicClientApplicationConfig *config = [[MSALPublicClientApplicationConfig alloc] initWithClientId:@"<your-client-id-here>"];
MSALPublicClientApplication *application = [[MSALPublicClientApplication alloc] initWithConfiguration:config error:&msalError];

Acquiring Your First Token

Swift

    let interactiveParameters = MSALInteractiveTokenParameters(scopes: scopes)
            application.acquireToken(with: interactiveParameters, completionBlock: { (result, error) in

                guard let authResult = result, error == nil else {
                    print(error!.localizedDescription)
                    return
                }

                // Get access token from result
                let accessToken = authResult.accessToken

                // You'll want to get the account identifier to retrieve and reuse the account for later acquireToken calls
                let accountIdentifier = authResult.account.homeAccountId?.identifier
            })

Objective-C

    MSALInteractiveTokenParameters *interactiveParams = [[MSALInteractiveTokenParameters alloc] initWithScopes:scopes];
    [application acquireTokenWithParameters:interactiveParams completionBlock:^(MSALResult *result, NSError *error) {
        if (!error)
        {
            // You'll want to get the account identifier to retrieve and reuse the account
            // for later acquireToken calls
            NSString *accountIdentifier = result.account.homeAccountId.identifier;

            NSString *accessToken = result.accessToken;
        }
        else
        {
            // Check the error
        }
    }];

Our library uses the ASWebAuthenticationSession for authentication on iOS 12 by default. See more information about default values, and support for other iOS versions Wiki

Silently Acquiring an Updated Token

Swift

guard let account = try? application.account(forHomeAccountId: accountIdentifier) else { return }
        let silentParameters = MSALSilentTokenParameters(scopes: scopes, account: account)
        application.acquireTokenSilent(with: silentParameters) { (result, error) in

            guard let authResult = result, error == nil else {

                let nsError = error! as NSError

                if (nsError.domain == MSALErrorDomain &&
                    nsError.code == MSALError.interactionRequired.rawValue) {

                    // Interactive auth will be required
                    return
                }
                return
            }

            // Get access token from result
            let accessToken = authResult.accessToken
        }

Objective-C

    NSError *error = nil;
    MSALAccount *account = [application accountForHomeAccountId:accountIdentifier error:&error];
    if (!account)
    {
        // handle error
        return;
    }

    MSALSilentTokenParameters *silentParams = [[MSALSilentTokenParameters alloc] initWithScopes:scopes account:account];
    [application acquireTokenSilentWithParameters:silentParams completionBlock:^(MSALResult *result, NSError *error) {
        if (!error)
        {
            NSString *accessToken = result.accessToken;
        }
        else
        {
            // Check the error
            if ([error.domain isEqual:MSALErrorDomain] && error.code == MSALErrorInteractionRequired)
            {
                // Interactive auth will be required
            }

            // Other errors may require trying again later, or reporting authentication problems to the user
        }
    }];

Responding to an Interaction Required Error

Occasionally user interaction will be required to get a new access token, when this occurs you will receive a MSALErrorInteractionRequired error when trying to silently acquire a new token. In those cases call acquireToken: with the same account and scopes as the failing acquireTokenSilent: call. It is recommended to display a status message to the user in an unobtrusive way before invoking interactive acquireToken: call.

For more information, please see the wiki.

Migrating from ADAL Objective-C

MSAL Objective-C is designed to support smooth migration from ADAL Objective-C library. For detailed design and instructions, follow this guide.

Additional guidance

Our wiki is intended to document common patterns, error handling and debugging, functionality (e.g. logging, telemetry), and active bugs.
You can find it here

Community Help and Support

We use Stack Overflow with the community to provide support. We highly recommend you ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.

If you find and bug or have a feature request, please raise the issue on GitHub Issues.

To provide a recommendation, visit our User Voice page.

Contribute

We enthusiastically welcome contributions and feedback. You can clone the repo and start contributing now. Read our Contribution Guide for more information.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Security Library

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 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.

Security Reporting

If you find a security issue with our libraries or services please report it to [email protected] with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty 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 and subscribing to Security Advisory Alerts.

License

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

Latest podspec

{
    "name": "MSAL",
    "version": "0.4.3",
    "summary": "Microsoft Authentication Library (MSAL) Preview for iOS",
    "description": "The MSAL library preview for iOS gives your app the ability to begin using the Microsoft Cloud by supporting Microsoft Azure Active Directory and Microsoft Accounts in a converged experience using industry standard OAuth2 and OpenID Connect. The library also supports Microsoft Azure B2C for those using our hosted identity management service.",
    "homepage": "https://github.com/AzureAD/microsoft-authentication-library-for-objc",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "authors": {
        "Microsoft": "[email protected]"
    },
    "social_media_url": "https://twitter.com/azuread",
    "platforms": {
        "ios": "10.0",
        "osx": "10.11"
    },
    "source": {
        "git": "https://github.com/AzureAD/microsoft-authentication-library-for-objc.git",
        "tag": "0.4.3",
        "submodules": true
    },
    "pod_target_xcconfig": {
        "CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF": "NO"
    },
    "default_subspecs": "app-lib",
    "prefix_header_file": "MSAL/src/MSAL.pch",
    "header_dir": "MSAL",
    "subspecs": [
        {
            "name": "app-lib",
            "source_files": [
                "MSAL/src/**/*.{h,m}",
                "MSAL/IdentityCore/IdentityCore/src/**/*.{h,m}"
            ],
            "ios": {
                "public_header_files": [
                    "MSAL/src/public/*.h",
                    "MSAL/src/public/ios/*.h",
                    "MSAL/src/public/configuration/**/*.h"
                ],
                "exclude_files": [
                    "MSAL/src/**/mac/*",
                    "MSAL/IdentityCore/IdentityCore/src/**/mac/*"
                ]
            },
            "osx": {
                "public_header_files": [
                    "MSAL/src/public/mac/*.h",
                    "MSAL/src/public/*.h",
                    "MSAL/src/public/configuration/**/*.h"
                ],
                "exclude_files": [
                    "MSAL/src/**/ios/*",
                    "MSAL/IdentityCore/IdentityCore/src/**/ios/*"
                ]
            },
            "requires_arc": true
        },
        {
            "name": "extension",
            "compiler_flags": "-DADAL_EXTENSION_SAFE=1",
            "source_files": [
                "MSAL/src/**/*.{h,m}",
                "MSAL/IdentityCore/IdentityCore/src/**/*.{h,m}"
            ],
            "ios": {
                "public_header_files": [
                    "MSAL/src/public/*.h",
                    "MSAL/src/public/ios/*.h",
                    "MSAL/src/public/configuration/**/*.h"
                ],
                "exclude_files": [
                    "MSAL/src/**/mac/*",
                    "MSAL/IdentityCore/IdentityCore/src/**/mac/*"
                ]
            },
            "osx": {
                "public_header_files": [
                    "MSAL/src/public/mac/*.h",
                    "MSAL/src/public/*.h",
                    "MSAL/src/public/configuration/**/*.h"
                ],
                "exclude_files": [
                    "MSAL/src/**/ios/*",
                    "MSAL/IdentityCore/IdentityCore/src/**/ios/*"
                ]
            },
            "requires_arc": true
        }
    ]
}

Pin It on Pinterest

Share This