Graph API Using Android Application

Introduction

 
This article demonstrates how to add Graph API using Android Application and get an access token and call Graph API or other APIs that require access tokens from Azure Active Directory v2. 
 

How does it work?

 
 
The sample created by this guide is based on a scenario where an Android application is used to query a Web API that accepts the token from Azure Active Directory v2.
 
Prerequisites
  • This article setup is focused on Android Studio, but any other Android application development environment is also acceptable.
  • Android SDK 21 or newer is required (SDK 25 is recommended).
  • Google Chrome or a web browser using Custom Tabs is required for this release of the Microsoft Authentication Library (MSAL) for Android. 
MSAL manages to cache and refreshing access tokens for you, so your application doesn't need to.
 
Step 1
 
Open the browser and search for Application Registration Portal (Microsoft) Click Here. Then, Login with your Outlook ID and give an application name followed by a click on "Create".
 
 
Step 2
    
Create a new API Registration page and then copy the displayed Application ID.
 
 
Step 3 
   
Next, give your application permissions. Click the add button. but default added User. Read option.
 
 
Step 4
 
Create a new project in Android Studio. When it prompts you to select the default activity, select Empty Activity and proceed.
 
 
Step 5 
  
Next, go to Gradle Scripts >> build.gradle (Module: app)
 
 
Select build.gradle page. The app Gradle compile code will appear. Just replace that the following code.
 
dependencies 
  1. compile 'com.android.volley:volley:1.0.0'  
  2. compile ('com.microsoft.identity.client:msal:0.1.1') {  
  3. exclude group: 'com.android.support', module: 'appcompat-v7' }  
buildTypes 
  1. release {  
  2.             minifyEnabled false  
  3.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  4.         }  
Step 6
 
Next, go to app >> res >> layout >>activity_main.xml. Select activity_main.xml page. The xml code will appear, Just replace the following code.
 
 
Change the activity layout from
 
"android.support.constraint.ConstrainstLayout" or other to "LinearLayout".
Add (android:orentation="verticle") property to LinearLayout, Copy and paste the following code. 
 
XML Code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:id="@+id/activity_main"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:background="#FFFFFF"  
  8.     android:orientation="vertical"  
  9.     tools:context="com.azuresamples.msalandroidapp.MainActivity">  
  10.   
  11.     <TextView  
  12.         android:id="@+id/welcome"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_marginLeft="10dp"  
  16.         android:layout_marginTop="15dp"  
  17.         android:text="Welcome, "  
  18.         android:textColor="#1A237E"  
  19.         android:textSize="50px"  
  20.         android:visibility="invisible" />  
  21.     <Button  
  22.         android:id="@+id/callGraph"  
  23.         android:text="Microsoft Sign in"  
  24.         android:textColor="#FFFFFF"  
  25.         android:background="#1A237E"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content"  
  28.         android:layout_marginTop="200dp"  
  29.         android:textAllCaps="false" />  
  30.     <TextView  
  31.         android:id="@+id/graphData"  
  32.         android:layout_width="match_parent"  
  33.         android:layout_height="wrap_content"  
  34.         android:layout_marginLeft="5dp"  
  35.         android:text="Getting Graph Data..."  
  36.         android:textColor="#3f3f3f"  
  37.         android:visibility="invisible" />  
  38.     <LinearLayout  
  39.         android:layout_width="match_parent"  
  40.         android:layout_height="0dip"  
  41.         android:layout_weight="1"  
  42.         android:gravity="center|bottom"  
  43.         android:orientation="vertical" >  
  44.         <Button  
  45.             android:text="Sign Out"  
  46.             android:layout_width="match_parent"  
  47.             android:layout_height="wrap_content"  
  48.             android:layout_marginBottom="15dp"  
  49.             android:textColor="#FFFFFF"  
  50.             android:background="#00a1f1"  
  51.             android:textAllCaps="false"  
  52.             android:id="@+id/clearCache"  
  53.             android:visibility="invisible" />  
  54.     </LinearLayout>  
  55.   
  56. </LinearLayout>   
Step 7 
  • Next, go to app >> java >> (company domain name) >> MainActivity. Select MainActivity page, The java code will appear. 
  • Add the following imports
 
Imports Code
  1. import android.app.Activity;  
  2. import android.content.Intent;  
  3. import android.support.v7.app.AppCompatActivity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import android.widget.TextView;  
  9. import android.widget.Toast;  
  10. import com.android.volley.*;  
  11. import com.android.volley.toolbox.JsonObjectRequest;  
  12. import com.android.volley.toolbox.Volley;  
  13. import org.json.JSONObject;  
  14. import java.util.HashMap;  
  15. import java.util.List;  
  16. import java.util.Map;  
  17. import com.microsoft.identity.client.*;  
Replace the MainActivity class with below
 
First the Registration Application ID.
  1. final static String CLIENT_ID = "[Enter the application Id here]";
Access the user read permission 
 
 
Java Code
  1. public class MainActivity extends AppCompatActivity {  
  2.   
  3.   
  4.     final static String CLIENT_ID = "Enter the Application Client ID";  
  5.     final static String SCOPES [] = {"https://graph.microsoft.com/User.Read"};  
  6.     final static String MSGRAPH_URL = "https://graph.microsoft.com/v1.0/me";  
  7.   
  8.   
  9.     private static final String TAG = MainActivity.class.getSimpleName();  
  10.     Button callGraphButton;  
  11.     Button signOutButton;  
  12.   
  13.   
  14.     private PublicClientApplication sampleApp;  
  15.     private AuthenticationResult authResult;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.activity_main);  
  21.   
  22.         callGraphButton = (Button) findViewById(R.id.callGraph);  
  23.         signOutButton = (Button) findViewById(R.id.clearCache);  
  24.   
  25.         callGraphButton.setOnClickListener(new View.OnClickListener() {  
  26.             public void onClick(View v) {  
  27.                 onCallGraphClicked();  
  28.             }  
  29.         });  
  30.   
  31.         signOutButton.setOnClickListener(new View.OnClickListener() {  
  32.             public void onClick(View v) {  
  33.                 onSignOutClicked();  
  34.             }  
  35.         });  
  36.   
  37.   
  38.         sampleApp = null;  
  39.         if (sampleApp == null) {  
  40.             sampleApp = new PublicClientApplication(  
  41.                     this.getApplicationContext(),  
  42.                     CLIENT_ID);  
  43.         }  
  44.   
  45.   
  46.         List<User> users = null;  
  47.   
  48.         try {  
  49.             users = sampleApp.getUsers();  
  50.   
  51.             if (users != null && users.size() == 1) {  
  52.   
  53.   
  54.                 sampleApp.acquireTokenSilentAsync(SCOPES, users.get(0), getAuthSilentCallback());  
  55.   
  56.             } else {  
  57.   
  58.             }  
  59.         } catch (MsalClientException e) {  
  60.             Log.d(TAG, "MSAL Exception Generated while getting users: " + e.toString());  
  61.   
  62.         } catch (IndexOutOfBoundsException e) {  
  63.             Log.d(TAG, "User at this position does not exist: " + e.toString());  
  64.         }  
  65.   
  66.     }  
  67.   
  68.   
  69.     @Override  
  70.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  71.         sampleApp.handleInteractiveRequestRedirect(requestCode, resultCode, data);  
  72.     }  
  73.   
  74.   
  75.     private void onCallGraphClicked() {  
  76.         sampleApp.acquireToken(getActivity(), SCOPES, getAuthInteractiveCallback());  
  77.   
  78.     }   
Setup Sign-out Process
 
Add the following method into the MainActivity class 
  1. // Setup Sign-out    
  2.     
  3.     private void onSignOutClicked() {    
  4.     
  5.     
  6.         List<User> users = null;    
  7.     
  8.         try {    
  9.             users = sampleApp.getUsers();    
  10.     
  11.             if (users == null) {    
  12.     
  13.     
  14.             } else if (users.size() == 1) {    
  15.     
  16.                 sampleApp.remove(users.get(0));    
  17.                 updateSignedOutUI();    
  18.     
  19.             }    
  20.             else {    
  21.     
  22.                 for (int i = 0; i < users.size(); i++) {    
  23.                     sampleApp.remove(users.get(i));    
  24.                 }    
  25.             }    
  26.     
  27.             Toast.makeText(getBaseContext(), "Signed Out!", Toast.LENGTH_SHORT)    
  28.                     .show();    
  29.     
  30.         } catch (MsalClientException e) {    
  31.             Log.d(TAG, "MSAL Exception Generated while getting users: " + e.toString());    
  32.     
  33.         } catch (IndexOutOfBoundsException e) {    
  34.             Log.d(TAG, "User at this position does not exist: " + e.toString());    
  35.         }    
  36.     }   
Call the Microsoft Graph API using the token you just obtained
 
Add the following methods into the MainActivity class 
  1.     private void callGraphAPI() {  
  2.         Log.d(TAG, "Starting volley request to graph");  
  3.   
  4.   
  5.         if (authResult.getAccessToken() == null) {return;}  
  6.   
  7.         RequestQueue queue = Volley.newRequestQueue(this);  
  8.         JSONObject parameters = new JSONObject();  
  9.   
  10.         try {  
  11.             parameters.put("key""value");  
  12.         } catch (Exception e) {  
  13.             Log.d(TAG, "Failed to put parameters: " + e.toString());  
  14.         }  
  15.         JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, MSGRAPH_URL,  
  16.                 parameters,new Response.Listener<JSONObject>() {  
  17.             @Override  
  18.             public void onResponse(JSONObject response) {  
  19.   
  20.                 Log.d(TAG, "Response: " + response.toString());  
  21.   
  22.                 updateGraphUI(response);  
  23.             }  
  24.         }, new Response.ErrorListener() {  
  25.             @Override  
  26.             public void onErrorResponse(VolleyError error) {  
  27.                 Log.d(TAG, "Error: " + error.toString());  
  28.             }  
  29.         }) {  
  30.             @Override  
  31.             public Map<String, String> getHeaders() throws AuthFailureError {  
  32.                 Map<String, String> headers = new HashMap<>();  
  33.                 headers.put("Authorization""Bearer " + authResult.getAccessToken());  
  34.                 return headers;  
  35.             }  
  36.         };  
  37.   
  38.         Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());  
  39.   
  40.         request.setRetryPolicy(new DefaultRetryPolicy(  
  41.                 3000,  
  42.                 DefaultRetryPolicy.DEFAULT_MAX_RETRIES,  
  43.                 DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));  
  44.         queue.add(request);  
  45.     }  
  46.   
  47.   
  48.     private void updateGraphUI(JSONObject graphResponse) {  
  49.         TextView graphText = (TextView) findViewById(R.id.graphData);  
  50.         graphText.setText(graphResponse.toString());  
  51.     }  
  52.   
  53. //  
  54.     private void updateSuccessUI() {  
  55.         callGraphButton.setVisibility(View.INVISIBLE);  
  56.         signOutButton.setVisibility(View.VISIBLE);  
  57.         findViewById(R.id.welcome).setVisibility(View.VISIBLE);  
  58.         ((TextView) findViewById(R.id.welcome)).setText("Welcome, " +  
  59.                 authResult.getUser().getName());  
  60.         findViewById(R.id.graphData).setVisibility(View.VISIBLE);  
  61.     }  
  62.   
  63.   
  64.     private void updateSignedOutUI() {  
  65.         callGraphButton.setVisibility(View.VISIBLE);  
  66.         signOutButton.setVisibility(View.INVISIBLE);  
  67.         findViewById(R.id.welcome).setVisibility(View.INVISIBLE);  
  68.         findViewById(R.id.graphData).setVisibility(View.INVISIBLE);  
  69.         ((TextView) findViewById(R.id.graphData)).setText("No Data");  
  70.     }  
  71.   
  72.   
  73.   
  74.     public Activity getActivity() {  
  75.         return this;  
  76.     }  
  77.   
  78.   
  79.     private AuthenticationCallback getAuthSilentCallback() {  
  80.         return new AuthenticationCallback() {  
  81.             @Override  
  82.             public void onSuccess(AuthenticationResult authenticationResult) {  
  83.   
  84.                 Log.d(TAG, "Successfully authenticated");  
  85.   
  86.   
  87.                 authResult = authenticationResult;  
  88.   
  89.   
  90.                 callGraphAPI();  
  91.   
  92.   
  93.                 updateSuccessUI();  
  94.             }  
  95.   
  96.             @Override  
  97.             public void onError(MsalException exception) {  
  98.   
  99.                 Log.d(TAG, "Authentication failed: " + exception.toString());  
  100.   
  101.                 if (exception instanceof MsalClientException) {  
  102.   
  103.                 } else if (exception instanceof MsalServiceException) {  
  104.   
  105.                 } else if (exception instanceof MsalUiRequiredException) {  
  106.   
  107.                 }  
  108.             }  
  109.   
  110.             @Override  
  111.             public void onCancel() {  
  112.   
  113.                 Log.d(TAG, "User cancelled login.");  
  114.             }  
  115.         };  
  116.     }  
  117.   
  118.   
  119.     private AuthenticationCallback getAuthInteractiveCallback() {  
  120.         return new AuthenticationCallback() {  
  121.             @Override  
  122.             public void onSuccess(AuthenticationResult authenticationResult) {  
  123.   
  124.                 Log.d(TAG, "Successfully authenticated");  
  125.                 Log.d(TAG, "ID Token: " + authenticationResult.getIdToken());  
  126.                 authResult = authenticationResult;  
  127.                 callGraphAPI();  
  128.                 updateSuccessUI();  
  129.             }  
  130.   
  131.             @Override  
  132.             public void onError(MsalException exception) {  
  133.   
  134.                 Log.d(TAG, "Authentication failed: " + exception.toString());  
  135.   
  136.                 if (exception instanceof MsalClientException) {  
  137.   
  138.                 } else if (exception instanceof MsalServiceException) {  
  139.   
  140.                 }  
  141.             }  
  142.   
  143.             @Override  
  144.             public void onCancel() {  
  145.   
  146.                 Log.d(TAG, "User cancelled login.");  
  147.             }  
  148.         };  
  149.     }  
  150. }  
Step 8
 
Next, go to app >> manifests >> AndroidMainfest.xml. Select the AndroidMainfest page, The xml code will appear. Just replace the following code.
 
 
Just Enable INTERNET and ACCESS_NETWORK_STATE. 
  1. <uses-permission android:name="android.permission.INTERNET"/>  
  2.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  
This registers a BrowserTabActivity to allow the OS to resume your application after completing the authentication.  
  1.         <activity  
  2.             android:name="com.microsoft.identity.client.BrowserTabActivity">  
  3.             <intent-filter>  
  4.                 <action android:name="android.intent.action.VIEW" />  
  5.                 <category android:name="android.intent.category.DEFAULT" />  
  6.                 <category android:name="android.intent.category.BROWSABLE" />  
  7.   
  8.                 <!--Add in your scheme/host from registered redirect URI-->  
  9.                 <data android:scheme="msale170b15e-0e09-4fa2-a68b-0896326d97bd"  
  10.                     android:host="auth" />  
  11.             </intent-filter>  
  12.         </activity>  
Step 9 
 
Next, go to Android Studio and Deploy the application. Select deployment target.
 
 
OUTPUT
 
Run the application in your desired emulator (Shift + F10). 
 
 
Finally, we have successfully created MGraph API using the Android application 


Similar Articles