Overview
The lab instructs students in configuring and running an Android app which allows the user to edit items in a SharePoint Task list.
Objectives
- Learn how to authenticate with Azure AD from Android using the **Azure Active Directory Authentication Library (ADAL) for Android**
- Learn how to consume SharePoint APIs from Android using the **Office 365 SDK for Android**
- Implement a new feature in the Android app
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
O365 DEVCamp Los Angeles June 16, 2015 Module 06 Hook into SharePoint APIs with ANDFROID
1. Module 6: Hooking into SharePoint APIs with Android
Registration for Los Angeles June 16 2015
http://aka.ms/O365campLA
2. Course Agenda
Office Camp
Module 1: Introduction to the Day
Module 2: Setting up the Environments
Module 3: Hooking into Apps for SharePoint
Module 4: Hooking into Office 365 APIs
Module 5: Hooking into Apps for Office
Module 6: Hooking into SharePoint APIs with Android
21. Start
User initiates API call
acquireTokenSilently()
callback(accessToken)
Complete API call
End
Cache valid? NO
YES
refreshToken()
Success?YES NO
Restart app for auth
End
storeTokens()
27. ListClient client = new ListClient(
sharePointUrl, //e.g. "http://mydomain.sharepoint.com/"
sharePointSitePath, //e.g. "/client/site"
credentials
);
Credentials credentials = new OAuthCredentials(accessToken);
28. final String listName = "My List";
//this produces the odata query: $filter=Title+eq+"My list"
Query query = QueryOperations.field("Title").eq(listName);
//we can attach callbacks to f which will run when the data is available
ListenableFuture<List<SPList>> f = client.getLists(query);
//Or... calling .get() will block this thread until the data is available
//DO NOT DO THIS ON THE UI THREAD!
List<SPList> results = f.get();
29. final String listName = "My List";
//this produces the odata query: $filter=startsWith(Title,"Item #")
Query query = QueryOperations.startsWith("Title", "Item #");
//we can attach callbacks to f which will run when the data is available
ListenableFuture<List<SPListItem>> f = client.getListItems(listName, query);
//Or... calling .get() will block this thread until the data is available
//DO NOT DO THIS ON THE UI THREAD!
List<SPListItem> results = f.get();
Hinweis der Redaktion
Android Studio is the current state-of-the-art for Android development. It is built on top of the IntelliJ IDEA IDE, a popular Java IDE developed by JetBrains.
The editor will feel familiar for users of JetBrain’s popular ReSharper plugin for Visual Studio.
Gradle makes the world go round.
Dependencies can be pulled from e.g. Maven Central or jCenter.
Android Studio automatically keeps it’s own project files in sync with the Gradle build files, so adding a dependency to a project is as simple as adding a line to the appropriate build.gradle file.
The above line of code adds a dependency on the Active Directory Authentication Library for Android, a library maintained by MSOpenTech.
The dependency is automatically downloaded in the background, so you immediately get autocomplete on all types in that library.
Use the Android SDK manager to download different SDK Levels.
The hands-on-lab will be targeting API Level 21 (Android 5.0.1 Lollipop), but should run fine on devices running API Levels as low as 18 (Android 4.3.1 KitKat).
This is the high-level architecture of our app and the services which it consumes.
Authentication is provided directly by Azure AD, via OAuth.
After authentication, we communicate with the O365 SharePoint instance via its REST APIs.
In this section we will look at authenticating an Android app with Azure AD using the Active Directory Library for Android
ADAL simplifies authentication with Azure AD. Provides support for user authentication via sign-in (UI) or refresh tokens.
Can be found on GitHub at https://github.com/AzureAD/azure-activedirectory-library-for-android
This does require you to have access to the Azure Active Directory for your O365 Instance.
You can do this by Adding a new Active Directory to your Azure Subscription, and selecting the “Use existing directory” option.
After completing this step, creating the Application is simple – we cover that in the lab.
First we must update the build.gradle file to include the ADAL.
Android Studio will prompt you to Sync the changes to the Gradle file – this downloads the dependency and puts it in the right place for the IDE to find it, enabling autocompletion etc.
Next we update the AndroidManifest.xml file with some permissions that ADAL requires (Internet/network permissions)
We must also register the AuthenticationActivity activity which does the heavy-lifting of the OAuth flow. ADAL launches this activity which allows the user to enter their credentials.
These basic code snippets must be added to your Activity class.
Step 4 is only required if you intend to call mContext.acquireToken which will automatically launch an instance AuthenticationActivity. The onActivityResult function is invoked when that activity completes with a result.
acquireToken launches the Oauth UI, and prompts the user to sign in with their O365 SharePoint credentials.
The returned AuthenticationResult instance contains an Access Token (which will expire) and a Refresh Token. The refresh token will also eventually expire, but only after a much longer time.
The callback argument is an instance of the AuthenticationCallback interface. Generally this is done using a Java Anonymous Class.
The callback is invoked by mContext.onActivityResult from the previous slide, so it is important to call that if you are using this function.
Note: ADAL automatically caches the access token and refresh token securely, so you don’t have to! It uses the Android secure keychain to do so.
The callback argument is an instance of the AuthenticationCallback interface. Generally this is done using a Java Anonymous Class.
Generally you will invoke acquireToken only when the user first starts the application, and then use acquireTokenSilently from then on. The ADAL automatically caches the Access Token and Refresh Token securely in the Android Keychain, and acquireTokenSilently attempts the following:
Return the current Access Token (if still valid)
Acquire a new Access Token using the current Refresh Token (if still valid)
If this function fails, you must prompt the user to sign in using acquireToken.
This function returns a new Access Token.
In this pattern full authentication is only done on application startup. The Splash Screen here is the gateway to your app – the user must authenticate to continue.
The app launches and starts the default activity or splash screen.
The user clicks “sign in” button, which invokes acquireToken()
The AuthenticationActivity is launched and the OAuth flow takes place – the user authenticates with Azure AD.
The authentication result (an Access Token and a Refresh Token) is cached securely. The Access Token is returned to the app.
The splash screen logic resumes and launches the next Activity.
Finally, the splash screen calls finish() to remove itself from the activity stack.
Next we write some code to support re-entrancy into potentially any location within the app.
The user may at any time dismiss our app, do some work and then return to our app after their token has expired.
In this situation we may need to refresh the Access Token or re-authenticate (or we may not).
The user initiates some action (e.g. Refresh the current view)
We first call acquireTokenSilently() to acquire an access token. We need to pass a callback because this function may asynchronously refresh the token.
If the cached token is still valid then acquireTokenSilently returns it immediately and we continue with the API call (this may happen completely synchronously).
Otherwise, the ADAL attempts to refresh the token using a cached refresh token. This happens asynchronously and requires an internet connection.
If successful, we continue with the API call.
If the refresh operation fails, then we must prompt the user to let them know, and restart the app so that they may authenticate again.
We can wrap all of this behaviour into a few helper methods.
Demo the authentication flow in StartActivity.
Demo the refresh token handling code in AuthUtil.ensureAuthenticated, DefaultAuthHandler and the two activites ListTasksActivity and EditTaskActivity.
The O365 SDK takes care of setting headers, serialization etc. Queries are automatically executed asynchronously on a background thread, so library functions may be safely called from the UI thread.
Can be found on GitHub at https://github.com/OfficeDev/Office-365-SDK-for-Android.
To use the SDK…
Create am OAuthCredentials object from the Access Token obtained using ADAL (you must already be authenticated to use this class).
Create an instance of ListClient. This class allows you to query and update SharePoint lists.
This library supports:
Authentication via Azure AD with OAuthCredentials
Basic authentication with BasicAuthenticationCredentials
Cookie authentication with CookieCredentials
This simple code queries sharepoint for all Lists with the title “My List”.
The object returned is a Future, also known as a Promise, which will be resolved when the call completes and the data is available. This means that the getLists call is non-blocking and can be safely used from the UI thread.
Warning! The final line calls ListenableFuture.get(), which blocks the current thread until the results are available. Do no use this on the UI thread!
This simple code queries sharepoint for all list items in the list with the name “My List”.
The object returned is a Future, also known as a Promise, which will be resolved when the call completes and the data is available. This means that the getListItems call is non-blocking and can be safely used from the UI thread.
Warning! The final line calls ListenableFuture.get(), which blocks the current thread until the results are available. Do no use this on the UI thread!
Demo the sharepoint data access code in TaskListItemDataSource.
Note that these functions are blocking and can only safely be called from a background thread!