An open API service indexing awesome lists of open source software.

https://github.com/azuread/microsoft-authentication-library-for-android

Microsoft Authentication Library (MSAL) for Android
https://github.com/azuread/microsoft-authentication-library-for-android

android azure-active-directory identity microsoft msal

Last synced: 3 months ago
JSON representation

Microsoft Authentication Library (MSAL) for Android

Awesome Lists containing this project

README

          

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

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

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)

## Using MSAL

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

### Requirements

- Min SDK Version 16+
- Target SDK Version 33+

### Step 1: Declare dependency on MSAL

Add to your app's build.gradle:

```gradle
dependencies {
implementation 'com.microsoft.identity.client:msal:4.9.+'
}
```

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'
}
```

### Step 2: Create your MSAL configuration file

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

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.

```javascript
{
"client_id" : "",
"redirect_uri" : "msauth:///",
"broker_redirect_uri_registered": true,
}
```

>NOTE: In the `redirect_uri`, the part `` 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.

### Step 3: Configure the AndroidManifest.xml

1. Request the following permissions via the Android Manifest

```XML


```

2. Configure an intent filter in the Android Manifest, using your redirect URI

>NOTE: Failure to include an intent filter matching the redirect URI you specify via configuration will result in a failed interactive token request. Please double check this!

```XML









```

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

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

String[] scopes = {"User.Read"};
IMultipleAccountPublicClientApplication mMultipleAccountApp = null;
IAccount mFirstAccount = null;

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

@Override
public void onError(MsalException exception) {
//Log Exception Here
}
});
```

2. Acquire a token interactively

```java

final AcquireTokenParameters.Builder builder = new AcquireTokenParameters.Builder();
builder.startAuthorizationFromActivity(activity)
.withScopes(scopes)
.withCallback(getAuthInteractiveCallback());
final AcquireTokenParameters parameters = builder.build();
mMultipleAccountApp.acquireToken(parameters);

...

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) {
//An exception from the client (MSAL)
} else if (exception instanceof MsalServiceException) {
//An exception from the server
}
}
@Override
public void onCancel() {
/* User canceled the 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
final AcquireTokenSilentParameters.Builder builder = new AcquireTokenSilentParameters.Builder();
builder.forAccount(account)
.withScopes(newScopes)
.fromAuthority(authority);
final AcquireTokenSilentParameters parameters = builder.build();
final IAuthenticationResult result = mMultipleAccountApp.acquireTokenSilent(parameters);
}

```

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

## Support

If you have any questions regarding the usage of MSAL Android, please utilize Chat with Copilot for assistance.
If you would like to report any bugs or feature requests, please create a support ticket with your Microsoft representative.

## Contribute

We enthusiastically welcome contributions and feedback. You should [clone the repo and start contributing now](https://github.com/AzureAD/microsoft-authentication-library-for-android/wiki/MSAL-Contributing).

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 [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

## Android Studio Build Requirement
Please note that this project uses [Lombok](https://projectlombok.org/) internally and while using Android Studio you will need to install [Lombok Plugin](https://plugins.jetbrains.com/plugin/6317-lombok) to get the project to build successfully within Android Studio.

## Recommendation

MSAL is a security library. It controls how users sign-in and access services. We recommend you always take the latest version of our library in your app when you can. We use [semantic versioning](http://semver.org) so you can control the risk of updating your app. For example, always downloading the latest minor version number (e.g. x.*y*.x) ensures you get the latest security and feature enhanements with the assurance that our API surface area has not changed. You can always see the latest version and release notes under the [Releases](https://github.com/AzureAD/microsoft-authentication-library-for-android/releases) tab of GitHub.

## Security Reporting

If you find a security issue with our libraries or services, please report the issue to [secure@microsoft.com](mailto:secure@microsoft.com) with as much detail as you can provide. 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](https://github.com/AzureAD/microsoft-authentication-library-for-android/issues) or any other public site. We will contact you shortly after receiving your issue report. We encourage you to get new security incident notifications by visiting [Microsoft technical security notifications](https://technet.microsoft.com/en-us/security/dd252948) to subscribe to Security Advisory Alerts.

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