Chris Risner . Com

Adding Authentication to Android Apps with Mobile Services

Posted on: 3/5/2013 5:32:10 AM by

Windows Azure Mobile ServicesWith today’s release of the Android SDK for Windows Azure Mobile Services, I thought it would be a good idea to post a walkthrough of adding some features into the quick start application.  The quick start, which you can download after spinning up a new Mobile Service, is a ToDo list.  It’s a rather simple application which already makes use of the structured data storage capabilities of Mobile Services to save, update, and read todo items.  In this post, we’ll look at how to make this todo list application an individualized application, meaning that each user has their own todo list and can’t see anyone else's data.  We’ll accomplish this by first requiring the user to log in.  Once that’s done, we can save each todo item so it’s tied to the logged in user and then make sure when we read the todo items back to the client application, we’re only getting the todo items for the logged in user.

Update: Android SDK Version Support

Since a few people have asked or thought differently, I wanted to clear up what versions of Android are supported by the Mobile Services SDK. The short answer is 2.2 (or level 8) and up. The Mobile Services SDK will build and run with any device running 2.2 or greater. The reason why the quick start application requires 4.2 (level 17) is that it has it's targetSdkVersion in it's manifest file set to 4.2. That's all. The app will still run on 2.2, it's just set to build against 4.2.

Creating a Mobile Service and getting the quick start app

Since I’ve covered this aspect of getting started with Mobile Services on several occasions (and it’s very straight forward) I’m going to glaze over some of the details.  If you don’t already have a Windows Azure account, you can sign up for one for free here.  Once you’ve done that, you’ll have access to create 10 free Mobile Services.  Next, you can watch this video to step through how to create your first Mobile Service and download the Android quick start application.  If you don’t feel like watching the video, I’ll summarize the steps you need to take after logging into the portal.

Start by clicking the + NEW button in the bottom left.  Select COMPUTE then MOBILE SERVICE and click CREATE.  Enter a unique name for your Mobile Service (this is how your Mobile Service will be labeled in the portal and part of the URL that will point at your service), choose if you want to create a new or use an existing database (if you have any) and pick a REGION (data center) before proceeding.  On the next screen, either choose to create a new server and enter admin credentials for it or pick an existing server / database and enter the creds for it.  Click the check mark and your Mobile Service will start being created.  After a little bit (it usually takes about twenty to thirty seconds) you can click on your Mobile Service and you’ll first be taken to the quick start page.  Here, under CHOOSE PLATFORM select ANDROID and then follow the guide under Create a new Android app.  Note that the first step isn’t necessary if you already have an IDE (we’ll assume Eclipse) with the Android SDK (at least 4.2) and ADT installed.  Once you’ve created the TodoItem Table you can download your project.  Next in Eclipse, go to Import under the File menu and choose Existing Projects into Workspace.  Navigate to your project and select it and it should be imported into Eclipse and show up in the Package Explorer.  If you want to, you can run the project now to see what the Todo list app looks like, but we’ll proceed on with adding authentication.

Setting up Google auth

Today we’re going to add in Google auth to our application.  We start this by going to the Google API Console.  Just like any of the other auth providers that Mobile Services supports (Facebook, Google, Microsoft, Twitter), the provider has to have some information about your application before you can get some information to do authentication.  If you’ve never been to the API console before, you should be easily directed to create a new project.  If not, open the drop down in the top left and go to Create under Other Projects (assuming you haven’t already created the project you want to use).  Name your project whatever you want (the name will only be used to identify it in the API console).  After creating or navigating to your project, go to the API Access link in the top left.  In the next screen you’ll be able to create an OAuth 2.0 client:

Google API Console API Access

Click that button and you’ll be able to enter some information about your app:

Create Client ID

Here just enter the information you want.  It’s not necessary for the Home Page URL to match your Mobile Service URL.  Once you’re done, click Next.  In the next screen, select Web application for the type.  In the Your site or hostname box, you’ll put the URL of your Mobile Service (visible in the portal Dashboard tab on the right side).  However, you’ll need to enter it with /login/google at the end:

Site or hostname for Google Auth

Once you tab out or leave that box, the /login/google will get hacked off and it will show up in the Redirect URI.  It’s really important to make sure this is right or your Google auth won’t work.  Once that’s correct, click the Create client ID button.  In the next screen, you’ll be able to see your project’s Client ID and Client secret:

google client id and secret

These two values need to be copied and placed into the portal.  Return to the Windows Azure portal and go to the Identity tab.  Locate the google settings on this page and copy those values over:

Google Auth in Portal

Once that’s done, click save.  Now before you can add auth to your app, you have one more step to take.  Go to the DATA tab, click the TodoItem table and go to the PERMISSIONS tab.  Change the permissions for each operation on the table to Only Authenticated Users:

Only Authenticated Users Permission

Click save and now we can move on to the app.

Adding authentication to your Android app

If you run the quick start application right now, you’ll have an error pop up after a few seconds.  This is because it’s unable to load the todo items because you aren’t passing a valid user object over (and we just restricted the table to require that).  If you look in Logcat you might even see this warning:

Authentication error: Unable to respond to any of these challenges: {}

Let’s fix that.  Open up ToDoActivity.java and start by adding these import statements to that class:

Once that is done drop the following method into the ToDoActivity class:

The first thing we’re doing in this method is calling the login method on our MobileServicesClient object.  We pass into this the auth provider type we want to authenticate with (Google in this case) and a UserAuthenticationCallback.  The callback has a method, onCompleted, that will be called whenever a response is returned from trying to authenticate (or if the user cancels).  Inside that callback, we’re showing a dialog to let the user if they were authenticated successfully or not and will call a new method, createTable, if it was a success.  Next go back to the onCreate method and remove all of the code inside the try catch block after you instantiate the MobileServiceClient and replace it with a call to authenticate().  The last thing we need to do is add the createTable method:

This method performs all of the code that we just removed from onCreate.  Now, run your application again.

Authenticating

Now when we run our application, the first thing we’ll get is a login view for Google:

Google Auth for WAMS

After you sign in and allow access, you’ll get a popup that says you’re logged in and you’ll then see all of the todo items that you’ve saved:

Todo Items after logging in

Now we just need to make the todo list personal.

Connecting saved items to users

The first thing we need to do to make these lists our own is to save the User ID whenever we save a todo item.  To do this, we’ll go to the portal and go to the DATA tab.  Open the TodoItem table and go to the SCRIPT tab.  Inside the Insert script, we’re going to add the userId to the item before we execute the request:

Now when you save a todo item if you browse the data on the portal, you’ll see a user ID has been saved for the latest item:

saved user ID

Now we just need to filter so that we only see our own items.

Filtering todo items by user

We could handle this in two ways.  We could do a where clause from the client and ask for only items that match my user ID.  However, when doing mobile app development, you never want to trust the client.  So instead, we’ll go the second route and do this on the server.  Return to the portal and go back to the SCRIPT tab for the TodoItem table and go to the Read script.  Before we execute the request, we’re going to add a new where clause to the query:

Now when we restart our application, we should only see the one todo item we’ve saved with the user ID:

Filtered Todo Items

Conclusion

Today we looked at how you can enhance the Android Mobile Services quick start application by adding authentication.  Furthermore, we looked at how we can take any application and make it a personal experience by saving and filtering information for the current user.  This just scratches the surface of what you can do with Windows Azure Mobile Services and your Android applications.  I’ll be posting more about the Android SDK and how you can really make your Android applications fly with Mobile Services in the future.

Bookmark and Share
Comments: 0
blog comments powered by Disqus