Giter VIP home page Giter VIP logo

ms-identity-android-kotlin's Introduction

languages page_type description products urlFragment
kotlin
sample
Integrate Microsoft Identity Platform authentication in your Android application.
azure
microsoft-entra-id
office-ms-graph

Use MSAL in an Android app to sign-in users and call Microsoft Graph

Getting Started Library API Reference Support

Build Badge

About the Sample

The MSAL Android library gives your app the ability to begin using the Microsoft identity platform by supporting Microsoft Entra ID and Microsoft Accounts in a converged experience using industry standard OAuth2 and OpenID Connect protocols.

This sample walks you through the process of integrating authentication with Microsoft Identity Platform (formerly Microsoft Entra ID for developers) in your android application. In this sample we'd walk you through the code you need to write in the various lifecycle events of your app to achieve the following objectives.

  • Sign-in a user
  • Device-wide SSO and Conditional Access support through the Auth Broker
  • Select between Single Account Mode and Multiple Account Mode
  • Get a token for the Microsoft Graph
  • Call the Microsoft Graph
  • Sign out the user

Scenario

This sample app is a multi-tenant app, which means that it can sign-in users from any Microsoft Entra tenant and Microsoft Accounts. It also demonstrates how a developer can build apps to connect with enterprise users and access their Azure + O365 data via Microsoft Graph. During the auth flow, the users will be required to sign-in first, if it is their first time signing-in to the app, the user would be asked to consent to the permissions required by the application.

The majority of the logic in this sample shows how to sign-in an end user and make a call to the Microsoft Graph to get basic information about the signed-in user.

Flowchart

Broker Authentication using MSAL

Microsoft provides applications for every mobile platform that allow for the bridging credentials across applications from different vendors and for enhanced features that require a single secure place from where to validate credentials. These applications are called Brokers. The brokers available for Android are Microsoft Authenticator and Company Portal. Learn more about Brokers here.

The MSAL for Android will automatically use the broker if they are present on the device.

Note: If you have older versions of Microsoft Authenticator or Company Portal App installed in the device where this sample application will be run, then the user might not be able to test the scenarios presented here. Please make sure that you have installed the latest version of Microsoft Authenticator or Company Portal on your device.

Single Account Mode

In the Single Account Mode, only one user can sign into the application at a time. If the app wants to support just one signed-in user, it is recommended to use the Single Account Mode.

The following code snippet from SingleAccountModeFragment class shows how the application is set to the Single Account Mode in the code:

PublicClientApplication.createSingleAccountPublicClientApplication(
    getContext(),
    R.raw.auth_config_single_account);

In the auth_config_single_account.json file, the account_mode is set as following:

"account_mode" : "SINGLE",

Single Account Mode with Shared Device Mode

Shared Device Mode will allow you to configure Android devices to be shared by multiple employees, while providing Microsoft Identity backed management of the device. Employees will be able to sign-in to their devices and access customer information quickly. When they are finished with their shift or task, they will be able to globally Sign-Out of the device and it will be immediately ready for the next employee to use.

Flowchart

Note

Applications that run on Shared Devices must be in Single Account Mode. Applications that only support Multiple Account Mode will not run on a Shared Device.

In the code, you can use the isSharedDevice() flag to determine if an application is in the Shared Device Mode. Your app can use this flag to modify UX accordingly.

Code snippet from SingleAccountModeFragment class showing usage of the isSharedDevice() flag:

deviceModeTextView.setText(mSingleAccountApp.isSharedDevice() ? "Shared" : "Non-Shared");

Note

You can only put a device in to Shared Mode using the Authenticator app and with a user who is in the Cloud Device Administrator role. You can configure the membership of your Organizational Roles by going to the Microsoft Entra admin center and selecting:

Microsoft Entra ID -> Roles and Administrators -> Cloud Device Administrator

Multiple Account Mode

In the Multiple Account Mode, the application supports multiple accounts and can switch between user accounts and get data from that user's account.

Code snippet from MultipleAccountModeFragment class shows how the application is set in the Multiple Account Mode in the code:

PublicClientApplication.createMultipleAccountPublicClientApplication(getContext(),
    R.raw.auth_config_multiple_account);

How to run this sample

To run this sample, you'll need:

  • Android SDK
  • An internet connection
  • a Microsoft Entra tenant. For more information on how to get a Microsoft Entra tenant, see How to get a Microsoft Entra tenant
  • One or more user accounts in your Microsoft Entra tenant.

Steps to Run the app

This sample ships with a default redirect_uri configured in the AndroidManifest.xml. In order for the default redirect_uri to work, this project must be built with the debug.keystore located in the gradle/ directory. To configure signing in Android Studio, see Sign Your App.

Step 1: Clone the code

From your shell or command line:

   git clone https://github.com/Azure-Samples/ms-identity-android-kotlin.git

The following steps have been carried out for android studio, but you can choose and work with any editor of your choice.

Open Android Studio, and select open an existing Android Studio project. Find the cloned project and open it.

Step 2: Run the sample

From menu, select Run > Run 'app'. Once the app launches,

  1. Click on the hamburger icon

    • Single Account: Select this to explore Single Account Mode

    • Multiple Account: Select this to explore Multiple Account Mode.

  2. Click on sign-in, it takes you to add account page.

  3. Add one or more accounts as per the device mode, and sign in with your test account.

  4. Once successfully signed-in, basic user details will be displayed.

To explore more about the application, follow on screen options.

This sample application is configured to run out-of-the-box. To register your own application and run the sample with those settings, follow below steps.

Register your Own Application (Optional)

To begin registering your app, start at the Microsoft Entra admin center

To create an app registration,

  1. Click New Registration.

  2. Name your app, select the audience you're targeting, and click Register.

  3. In the Overview > Sign in users in 5 minutes > Android.

    • Click on Make this changes for me.
    • Enter the Package Name from your Android Manifest.
    • Generate a Signature Hash. Follow the instructions in the portal.
  4. Hit the Make updates button. Note the MSAL Configuration as it is used later in AndroidManifest.xml and auth_config.json.

Configure the sample application with your app registration by replacing the sample code in auth_config.json and AndroidManifest.xml

  1. Copy and paste the MSAL Configuration JSON from the Microsoft Entra admin center into auth_config.json.

  2. Inside the AndroidManifest.xml, replace android:host and android:path with the same info saved in above step. - auth_config.json contains this information as a reference inside the redirect_uri field. - The Signature Hash should NOT be URL encoded in the AndroidManifest.xml. Refer Microsoft Entra ID Android Quickstart for more details

From menu, select Build > Clean Project and Run > Run 'app'.

About the code

The following code fragments walk through features that MSAL can implement.

SingleAccountModeFragment class

Contains code showing how the Single Account Mode is implemented. The includes authentication, obtaining the token, and making a Graph API call using the obtained token.

The following steps give you more details.

  1. Create a SingleAccount PublicClientApplication:

    PublicClientApplication.createSingleAccountPublicClientApplication(
        context as Context,
        R.raw.auth_config_single_account,
        object : IPublicClientApplication.ISingleAccountApplicationCreatedListener {
            override fun onCreated(application: ISingleAccountPublicClientApplication) {
            }
    
            override fun onError(exception: MsalException) {
            }
        })
  2. Signing in a user:

    mSingleAccountApp!!.signIn(activity as Activity, "", getScopes(), getAuthInteractiveCallback())
  3. Acquiring token:

    • Interactive:
    mSingleAccountApp!!.acquireToken(activity!!, getScopes(), getAuthInteractiveCallback())
    • Silent:
    mSingleAccountApp!!.acquireTokenSilentAsync(getScopes(), AUTHORITY, getAuthSilentCallback())
  4. Calling Graph API to get basic user details and displaying data:

    private fun callGraphAPI(authenticationResult: IAuthenticationResult) {
        MSGraphRequestWrapper.callGraphAPIWithVolley(
            context as Context,
            msgraph_url.text.toString(),
            authenticationResult.accessToken,
            Response.Listener<JSONObject> { response ->
                /* Successfully called graph, process data and send to UI */
                Log.d(TAG, "Response: $response")
                displayGraphResult(response)
            },
            Response.ErrorListener { error ->
                Log.d(TAG, "Error: $error")
                displayError(error)
            })
    }
  5. Sign-out:

    mSingleAccountApp!!.signOut(object : ISingleAccountPublicClientApplication.SignOutCallback {
        override fun onSignOut() {
        }
    
        override fun onError(exception: MsalException) {
        }
    });

    When sign-out is performed it removes the signed-in account and cached tokens from this app.

MultipleAccountModeFragment class

Contains code showing how the Multiple Account Mode is implemented. The includes authentication, obtaining the token, and making a Graph API call using the obtained token.

  1. Create a MultipleAccount PublicClientApplication:

    PublicClientApplication.createMultipleAccountPublicClientApplication(
        context as Context,
        R.raw.auth_config_multiple_account,
        object : IPublicClientApplication.IMultipleAccountApplicationCreatedListener {
            override fun onCreated(application: IMultipleAccountPublicClientApplication) {
                mMultipleAccountApp = application
            }
    
            override fun onError(error: MsalException){
            }
        });
  2. Acquiring token:

    • Interactive:
    mMultipleAccountApp!!.acquireToken(activity as Activity, getScopes(), getAuthInteractiveCallback())
    • Silent:
    mMultipleAccountApp.acquireTokenSilentAsync(getScopes(),
        accountList.get(accountListSpinner.getSelectedItemPosition()),
            AUTHORITY,
            getAuthSilentCallback());
  3. Get Accounts:

    mMultipleAccountApp!!.acquireTokenSilentAsync(
                getScopes(),
                accountList!![account_list.selectedItemPosition],
                AUTHORITY,
                getAuthSilentCallback()
            )
  4. Remove account:

     mMultipleAccountApp!!.removeAccount(
        accountList!![account_list.selectedItemPosition],
        object : IMultipleAccountPublicClientApplication.RemoveAccountCallback {
            override fun onRemoved() {
    
            }
    
            override fun onError(exception: MsalException) {
    
            }
        })

Feedback, 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 enhancements 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.

Other samples and documentation

ms-identity-android-kotlin's People

Contributors

didunayodeji avatar hamiltonha avatar microsoftopensource avatar msftgits avatar negoe avatar shoatman avatar yoelhor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ms-identity-android-kotlin's Issues

App crashes on devices below API 24

The app crashes on devices with an API below 24. Root cause is that the drawables are in the drawable-v24 folder, and so are not found at runtime.

The minSdk in build.gradle is set at 19, but should probably be 21, since several of the required assets are only available in vector drawable form? I don't recall if the support libraries do vector asset handling for APIs below 21.

Not Able to access outlook accounts like other ms apps like yammer and to do list.

Hi @shoatman can you look into this , i am not able to access outlook accounts in my device on login screen

https://stackoverflow.com/questions/58202286/login-always-opens-web-dialog-even-though-native-microsoft-apps-are-installed-m

one more thing, is it related to this error ?
This request is not eligible to use the broker. Do not check sharedDevice mode and return false immediately. Android 25

i have checked the yammer app and noticed that they have token manager and token services to get shared accounts list on the device to short logged in but not able to find the same way with this sample.

Please guide me on this.

Jetpack Compose

Is there any success or progress to implement the login using the jetpack compose?

Clicking home button in middle of a sign in process, and try to sign in again. No sign in screen is opening

We made this app a default launcher by changing the manifest file where we added for MainActivity. Now in the app we hit the sign in button. When it opens the MS sign in screen, I hit the home button which navigates back to the home screen of the launcher. When the sign in button is clicked again, nothing is happening.

In our app(which happens to be a launcher too):
We have a launcher developed in Kotlin where we have integrated Microsoft Sign in. When we click on the sign in button and it goes to Microsoft Sign-in page, we click on the android home button. Again, from Home Screen if we try to sign in, it does nothing (shows a loader as per the code while trying to open Microsoft sign-in page). It seems that upon clicking on home button, the Microsoft sign-in page instance is not getting closed/deleted, which results in no error and the screen keeps loading

Not able to authenticate or access account

Hi @shoatman,

I hope you are fine and doing well. I am facing one issue related to Azure authentication in Android.

I have integrated the MSAL library for authentication and it’s working fine if I am connected to public Wi-Fi, but facing issue when I am connected to secure network
using VPN.

Is there any way I can add proxy or authenticate the user through any web API keeping in secure network.

Is there any possibility I can authenticate by any means by keeping in secure network.

App crashes with "Don't keep activities" setting

This sample assumes that it is run on a device with sufficient memory to make sure that the activity launching the authentication flow is still alive to receive the result via AuthenticationCallback. This assumption might not be true on low-memory devices.
Android's "Don't keep activities" allows to simulate a scenario where the Android system has killed the activity.
When running the app under this condition, it crashes:

java.lang.NullPointerException
at com.azuresamples.msalandroidkotlinapp.SingleAccountModeFragment.callGraphAPI(SingleAccountModeFragment.kt:307)
at com.azuresamples.msalandroidkotlinapp.SingleAccountModeFragment.access$callGraphAPI(SingleAccountModeFragment.kt:58)
at com.azuresamples.msalandroidkotlinapp.SingleAccountModeFragment$authInteractiveCallback$1.onSuccess(SingleAccountModeFragment.kt:279)
at com.microsoft.identity.client.PublicClientApplication.postAuthResult(PublicClientApplication.java:2351)
at com.microsoft.identity.client.SingleAccountPublicClientApplication$3.onTaskCompleted(SingleAccountPublicClientApplication.java:443)
at com.microsoft.identity.client.SingleAccountPublicClientApplication$3.onTaskCompleted(SingleAccountPublicClientApplication.java:434)
at com.microsoft.identity.common.java.controllers.CommandDispatcher.commandCallbackOnTaskCompleted(CommandDispatcher.java:650)
at com.microsoft.identity.common.java.controllers.CommandDispatcher.access$1000(CommandDispatcher.java:99)
at com.microsoft.identity.common.java.controllers.CommandDispatcher$4.run(CommandDispatcher.java:626)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)

Conditional Access Policies by selecting this app is ignored

I have set Conditional Access Policies on the Azure Portal Intune settings for this app, but it seems to be ignored and I can sign in on incompliant devices.

  1. Sign in your Azure Portal on PC.
  2. Select "Intune".
  3. Select "Conditional Access".
  4. Create New policy with some settings.
  • "Users and groups" to "All users".
  • "Cloud apps or actions" to "Select apps" including "Azure Samples - Android".
  • "Conditions" - "Device platforms" to "Any device".
  • "Grant" to "Grant access" with "Require device to be marked as compliant" checked.
  • "Enable policy" to "On"
  1. Set Device compliance policy.
  • Add Compliance setting: e.g."Require a password to unlock mobile devices."
  • Set action "Mark device noncompliant" to "Immediately"
    Set Conditional Access on the Azure Portal Intune

After the above set, on the device where Intune is not installed, launch Azure Samples app, press "SIGN IN", enter your Azure account and password.
-> Sign-in is not blocked. it should be blocked on the incompliant device.

If "Cloud apps or actions" is set to "All cloud apps", Sign-in is blocked.
スクリーンショット 2020-07-12 16 57 04

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.