Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update SDK readme with native authentication content #2051

Open
wants to merge 20 commits into
base: dev
Choose a base branch
from
Open
Changes from 16 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
177 changes: 82 additions & 95 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
Microsoft Authentication Library (MSAL) for Android
==============================================
# Microsoft Authentication Library (MSAL) for Android

|[📚Documentation](https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-android) | [ 🚀 Getting Started](https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-mobile-app-android-sign-in) | [💻 Sample Code](https://github.com/AzureAD/microsoft-authentication-library-for-android/wiki/MSAL-Code-Samples)| [ 📖 Library Reference](http://javadoc.io/doc/com.microsoft.identity.client/msal) | [🛠️ Support](README.md#community-help-and-support) | [🌐 Docs Site](https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-mobile-overview)
| --- | --- | --- | --- | --- | --- |
| Documentation | Sample Code | Library Reference | Support |
|-------------------------------|---------------------------|-------------------|---------|
| [MSAL Android documentation](https://learn.microsoft.com/en-us/entra/msal/android/) | &#8226; [Microsoft Entra ID (workforce samples)](https://learn.microsoft.com/en-us/entra/identity-platform/sample-v2-code?tabs=apptype#mobile)<br/>&#8226; [Microsoft Entra External ID (customer samples)](https://learn.microsoft.com/en-us/entra/external-id/customers/samples-ciam-all?tabs=apptype#mobile) | [ MSAL Android reference](http://javadoc.io/doc/com.microsoft.identity.client/msal) | [Get support](README.md#community-help-and-support) |


## Introduction
The Microsoft Authentication Library (MSAL) for Android enables developers to acquire security tokens from the Microsoft identity platform to authenticate users and access secured web APIs for their Android based applications.
The MSAL library for Android gives your app the ability to use the [Microsoft Cloud](https://cloud.microsoft.com) by supporting [Microsoft Azure Active Directory](https://azure.microsoft.com/services/active-directory/) and [Microsoft Personal Accounts](https://account.microsoft.com) using industry standard OAuth2 and OpenID Connect. The library also supports [Azure AD B2C](https://azure.microsoft.com/services/active-directory-b2c/).

[![Version Badge](https://img.shields.io/maven-central/v/com.microsoft.identity.client/msal.svg)](https://repo1.maven.org/maven2/com/microsoft/identity/client/msal/)

### :exclamation: Migrating from ADAL
## Overview

The Microsoft Authentication Library (MSAL) for Android is an auth SDK that can be used to seamlessly integrate authentication into your apps using industry standard OAuth2 and OpenID Connect protocols. It allows you to sign in users or apps with Microsoft identities. These identities include Microsoft Entra ID work and school accounts, Microsoft personal accounts, social accounts, and customer accounts.

The Microsoft Authentication Library (MSAL) for Android enables developers to acquire tokens from the Microsoft identity platform using OAuth2 and OpenID Connect protocol to authenticate users and access secure web APIs for their Android based applications. The library supports multiple authentication scenarios such as [single sign-on](https://learn.microsoft.com/en-us/entra/msal/android/single-sign-on) (SSO), brokered authentication, and [Conditional Access](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context).

#### Native authentication support in MSAL

By default, MSAL uses the standard, browser-delegated authentication flow where you rely on the user's browser to handle the sign-in experience. This browser-based experience is the default authentication method for work and school accounts as well as personal Microsoft accounts.

Dickson-Mwendia marked this conversation as resolved.
Show resolved Hide resolved
To support Microsoft Entra External ID scenarios, MSAL Android now offers Native authentication that allows you to customize the sign-in experiences within your mobile app. With native authentication, users are guided through a rich, native, mobile-first sign-up and sign-in journey without leaving the app. The native authentication feature is only available for mobile apps on [External ID for customers](https://learn.microsoft.com/en-us/entra/external-id/customers/concept-native-authentication).

negoe marked this conversation as resolved.
Show resolved Hide resolved
When implementing authentication for mobile apps on External ID, you can choose between browser-delegated authentication and native authentication. In browser-delegated authentication, users are taken to the browser for authentication and then redirected back to the app when the sign-in process is complete. Learn how you can [choose the right authentication option](https://learn.microsoft.com/en-us/entra/external-id/customers/concept-native-authentication#when-to-use-native-authentication) for your mobile app.

negoe marked this conversation as resolved.
Show resolved Hide resolved
## Getting started

To use MSAL Android in your application, you need to register your application in the Microsoft Entra Admin center and configure your Android project. Since MSAL Android supports both browser-delegated and native authentication experiences, follow the steps in the following tutorials based on your scenario.

* For browser-delegated authentication scenarios, refer to the quickstart, [Sign in users and call Microsoft Graph from an Android app](https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-mobile-app-android-sign-in).

negoe marked this conversation as resolved.
Show resolved Hide resolved
* For native authentication scenarios, refer to the Microsoft Entra External ID sample guide, [Tutorial: Prepare your Android app for native authentication](https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-native-authentication-prepare-android-app).


ADAL Android was deprecated on June 2023. We do not support ADAL. See the [ADAL to MSAL migration guide for Android](https://docs.microsoft.com/azure/active-directory/develop/migrate-android-adal-msal)
## Migrating from ADAL

## Using MSAL
The Azure Active Directory Authentication Library (ADAL) for Android has been deprecated effective June 2023. Follow the [ADAL to MSAL migration guide for Android](https://docs.microsoft.com/azure/active-directory/develop/migrate-android-adal-msal) to avoid putting your app's security at risk.

- Before you can get a token from Azure AD v2.0 or Azure AD B2C, you'll need to register an application. To register your app, use [the Azure portal](https://aka.ms/AppRegistrations). For Azure AD B2C, checkout [how to register your app with B2C](https://docs.microsoft.com/azure/active-directory-b2c/active-directory-b2c-app-registration).
## Using MSAL Android

### Requirements

Expand All @@ -27,41 +44,62 @@ ADAL Android was deprecated on June 2023. We do not support ADAL. See the [ADAL

### Step 1: Declare dependency on MSAL

Add to your app's build.gradle:
Add the following dependencies to your app's build.gradle:

```gradle
dependencies {
implementation 'com.microsoft.identity.client:msal:4.9.+'
implementation 'com.microsoft.identity.client:msal:5.1.0'
negoe marked this conversation as resolved.
Show resolved Hide resolved
}
```

Please also add the following lines to your repositories section in your gradle script:

```gradle
maven {
url 'https://pkgs.dev.azure.com/MicrosoftDeviceSDK/DuoSDK-Public/_packaging/Duo-SDK-Feed/maven/v1'
maven {
url 'https://pkgs.dev.azure.com/MicrosoftDeviceSDK/DuoSDK-Public/_packaging/Duo-SDK-Feed/maven/v1'
Dickson-Mwendia marked this conversation as resolved.
Show resolved Hide resolved
name 'Duo-SDK-Feed'
}
```

Note: We recommend using the latest version of our library when setting up your application. Check the [MSAL Android Releases](https://github.com/AzureAD/microsoft-authentication-library-for-android/releases) page.

### Step 2: Create your MSAL configuration file

[Configuration Documentation](https://docs.microsoft.com/azure/active-directory/develop/msal-configuration)
**Browser-delegated authentication:**

It's simplest to create your configuration file as a "raw" resource file in your project resources. You'll be able to refer to this using the generated resource identifier when constructing an instance of PublicClientApplication. If you are registering your app in the portal for the first time, you will also be provided with this config JSON.
Create your configuration file as a "raw" resource in your project. Refer to it using the generated resource identifier when constructing a `PublicClientApplication` instance. If you're registering your app in the Microsoft Entra admin center for the first time, you'll also be provided with the detailed MSAL [Android configuration file](https://learn.microsoft.com/en-us/entra/msal/android/msal-configuration)

```javascript
```json
{
"client_id" : "<YOUR_CLIENT_ID>",
"redirect_uri" : "msauth://<YOUR_PACKAGE_NAME>/<YOUR_BASE64_URL_ENCODED_PACKAGE_SIGNATURE>",
"broker_redirect_uri_registered": true,
}
```

>NOTE: In the `redirect_uri`, the part `<YOUR_PACKAGE_NAME>` refers to the package name returned by the `context.getPackageName()` method. This package name is the same as the [`application_id`](https://developer.android.com/studio/build/application-id) defined in your `build.gradle` file.

>NOTE: This is the minimum required configuration. MSAL relies on the defaults that ship with the library for all other settings. Please refer to the [configuration file documentation](https://docs.microsoft.com/azure/active-directory/develop/msal-configuration) to understand the library defaults.
In the `redirect_uri`, the `<YOUR_PACKAGE_NAME>` refers to the package name returned by the `context.getPackageName()` method. This package name is the same as the [`application_id`](https://developer.android.com/studio/build/application-id) defined in your `build.gradle` file.

The values above are the minimum required configuration. MSAL relies on the defaults that ship with the library for all other settings. Please refer to the [MSAL Android configuration file documentation](https://learn.microsoft.com/en-us/entra/msal/android/msal-configuration) to understand the library defaults.

**Native authentication:**

1. Right-click res and choose New > Directory. Enter raw as the new directory name and select OK.
1. In this new folder (app > src > main > res > raw), create a new JSON file called auth_config_native_auth.json and paste the following template MSAL Configuration:

```json
{
"client_id": "Enter_the_Application_Id_Here",
"authorities": [
{
"type": "CIAM",
"authority_url": "https://Enter_the_Tenant_Subdomain_Here.ciamlogin.com/Enter_the_Tenant_Subdomain_Here.onmicrosoft.com/"
}
],
"challenge_types": ["oob"],
"logging": {
"pii_enabled": false,
"log_level": "INFO",
"logcat_enabled": true
}
}
```

### Step 3: Configure the AndroidManifest.xml
### Step 3: Configure the AndroidManifest.xml for browser-delegated authentication

1. Request the following permissions via the Android Manifest

Expand Down Expand Up @@ -90,94 +128,43 @@ It's simplest to create your configuration file as a "raw" resource file in your
</activity>
```

>NOTE: Please refer to [this FAQ](https://github.com/AzureAD/microsoft-authentication-library-for-android/wiki/MSAL-FAQ#redirect-uri-issues) for more information on common redirect uri issues.
>NOTE: Please refer to the [MSAL Android FAQ](https://learn.microsoft.com/en-us/entra/msal/android/frequently-asked-questions) for more information on common redirect uri issues.

### Step 4: Create an MSAL PublicClientApplication

>NOTE: In this example we are creating an instance of MultipleAccountPublicClientApplication, which is designed to work with apps that allow multiple accounts to be used within the same application. If you would like to use SingleAccount mode, refer to the [single vs. multi account documentation](https://docs.microsoft.com/azure/active-directory/develop/single-multi-account). You can also check out the [quickstart](https://docs.microsoft.com/azure/active-directory/develop/quickstart-v2-android) for examples of how this is used.

1. Create a new MultipleAccountPublicClientApplication instance.

```Java
**Browser-delegated authentication**

String[] scopes = {"User.Read"};
IMultipleAccountPublicClientApplication mMultipleAccountApp = null;
IAccount mFirstAccount = null;
For browser-delegated authentication, you create an instance of the PublicClientApplication, before you can acquire a token silently or interactively.

```java
PublicClientApplication.createMultipleAccountPublicClientApplication(getContext(),
R.raw.msal_config,
new IPublicClientApplication.IMultipleAccountApplicationCreatedListener() {
@Override
public void onCreated(IMultipleAccountPublicClientApplication application) {
mMultipleAccountApp = application;
}

Dickson-Mwendia marked this conversation as resolved.
Show resolved Hide resolved
@Override
public void onError(MsalException exception) {
//Log Exception Here
}
});
});
```

2. Acquire a token interactively

```java
Learn how to [instantiate your client application and acquire tokens](https://learn.microsoft.com/en-us/entra/msal/android/acquire-tokens) in the official MSAL Android documentation.

mMultipleAccountApp.acquireToken(this, SCOPES, getAuthInteractiveCallback());

private AuthenticationCallback getAuthInteractiveCallback() {
return new AuthenticationCallback() {
@Override
public void onSuccess(IAuthenticationResult authenticationResult) {
/* Successfully got a token, use it to call a protected resource */
String accessToken = authenticationResult.getAccessToken();
// Record account used to acquire token
mFirstAccount = authenticationResult.getAccount();
}
@Override
public void onError(MsalException exception) {
if (exception instanceof MsalClientException) {
//And exception from the client (MSAL)
} else if (exception instanceof MsalServiceException) {
//An exception from the server
}
}
@Override
public void onCancel() {
/* User canceled the authentication */
}
};
}
```
**Native authentication**

3. Acquire a token silently

```java

/*
Before getting a token silently for the account used to previously acquire a token interactively, we recommend that you verify that the account is still present in the local cache or on the device in case of brokered auth

Let's use the synchronous methods here which can only be invoked from a Worker thread
*/

//On a worker thread
IAccount account = mMultipleAccountApp.getAccount(mFirstAccount.getId());

if(account != null){
//Now that we know the account is still present in the local cache or not the device (broker authentication)

//Request token silently
String[] newScopes = {"Calendars.Read"};

String authority = mMultipleAccountApp.getConfiguration().getDefaultAuthority().getAuthorityURL().toString();

//Use default authority to request token from pass null
IAuthenticationResult result = mMultipleAccountApp.acquireTokenSilent(newScopes, account, authority);
}
For native authentication, you create an instance of the client application as follows:

```kotlin
authClient = PublicClientApplication.createNativeAuthPublicClientApplication(
this,
R.raw.auth_config_native_auth
)
```

Learn more by following the [Native auth Android app tutorial](https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-native-authentication-prepare-android-app#create-sdk-instance).

## ProGuard

MSAL uses reflection and generic type information stored in `.class` files at runtime to support various persistence and serialization related functionalities. Accordingly, library support for minification and obfuscation is limited. A default configuration is shipped with this library; please [file an issue](https://github.com/AzureAD/microsoft-authentication-library-for-android/issues/new/choose) if you find any issues.

## Community Help and Support
Expand Down
Loading