This topic shows you how to authenticate users in Azure Mobile Services from your iOS app. In this tutorial, you add authentication to the quickstart project using an identity provider that is supported by Mobile Services. After being successfully authenticated and authorized by Mobile Services, the user ID value is displayed.
This tutorial walks you through these basic steps to enable authentication in your app:
- Register your app for authentication and configure Mobile Services
- Restrict table permissions to authenticated users
- Add authentication to the app
- Storing authentication tokens in your app
This tutorial is based on the Mobile Services quickstart. You must also first complete the tutorial Get started with Mobile Services.
Completing this tutorial requires XCode 4.5 and iOS 5.0 or later versions.
Register your app for authentication and configure Mobile Services
To be able to authenticate users, you must register your app with an identity provider. You must then register the provider-generated client secret with Mobile Services.
- Log on to the Azure Management Portal, click Mobile Services, and then click your mobile service.
- Click the Dashboard tab and make a note of the Mobile Service URL value.You may need to provide this value to the identity provider when you register your app.
- Choose a supported identity provider from the list below and follow the steps to register your app with that provider:Remember to make a note of the client identity and secret values generated by the provider.SECURITY NOTEThe provider-generated secret is an important security credential. Do not share this secret with anyone or distribute it with your app.
- Back in the Management Portal, click the Identity tab, enter the app identifier and shared secret values obtained from your identity provider, and click Save.Both your mobile service and your app are now configured to work with your chosen authentication provider.
Restrict permissions to authenticated users
- In the Management Portal, click the Data tab, and then click the TodoItem table.
- Click the Permissions tab, set all permissions to Only authenticated users, and then click Save. This will ensure that all operations against the TodoItem table require an authenticated user. This also simplifies the scripts in the next tutorial because they will not have to allow for the possibility of anonymous users.
- In Xcode, open the project that you created when you completed the tutorial Get started with Mobile Services.
- Press the Run button to build the project and start the app in the iPhone emulator; verify that an unhandled exception with a status code of 401 (Unauthorized) is raised after the app starts.This happens because the app attempts to access Mobile Services as an unauthenticated user, but the TodoItem table now requires authentication.
Next, you will update the app to authenticate users before requesting resources from the mobile service.
Add authentication to the app
- Open the project file QSTodoListViewController.m and in the viewDidLoad method, remove the following code that reloads the data into the table:
[self refresh];
- Just after the viewDidLoad method, add the following code:
- (void)viewDidAppear:(BOOL)animated { MSClient *client = self.todoService.client; if (client.currentUser != nil) { return; } [client loginWithProvider:@"facebook" controller:self animated:YES completion:^(MSUser *user, NSError *error) { [self refresh]; }]; }
NOTEIf you are using an identity provider other than Facebook, change the value passed to loginWithProvider above to one of the following: microsoftaccount, facebook, twitter, google, or windowsazureactivedirectory. - Press the Run button to build the project, start the app in the iPhone emulator, then log-on with your chosen identity provider.When you are successfully logged-in, the app should run without errors, and you should be able to query Mobile Services and make updates to data.
Storing authentication tokens in your app
The previous example showed a standard sign-in, which requires the client to contact both the identity provider and the mobile service every time that the app starts. Not only is this method inefficient, you can run into usage-relates issues should many customers try to start you app at the same time. A better approach is to cache the authorization token returned by Mobile Services and try to use this first before using a provider-based sign-in.
NOTE:
You can cache the token issued by Mobile Services regardless of whether you are using client-managed or service-managed authentication. This tutorial uses service-managed authentication.
- The recommended way to encrypt and store authentication tokens on an iOS client is use the Keychain. To do this, create a class KeychainWrapper, copying KeychainWrapper.m and KeychainWrapper.h from the LensRocket sample. We use this KeychainWrapper as the KeychainWrapper defined in Apple's documentation does not account for automatic reference counting (ARC).
- Open the project file QSTodoListViewController.m and add the following code:
- (void) saveAuthInfo{ [KeychainWrapper createKeychainValue:self.todoService.client.currentUser.userId forIdentifier:@"userid"]; [KeychainWrapper createKeychainValue:self.todoService.client.currentUser.mobileServiceAuthenticationToken forIdentifier:@"token"]; } - (void)loadAuthInfo { NSString *userid = [KeychainWrapper keychainStringFromMatchingIdentifier:@"userid"]; if (userid) { NSLog(@"userid: %@", userid); self.todoService.client.currentUser = [[MSUser alloc] initWithUserId:userid]; self.todoService.client.currentUser.mobileServiceAuthenticationToken = [KeychainWrapper keychainStringFromMatchingIdentifier:@"token"]; } }
- At the end of the viewDidAppear method in QSTodoListViewController.m, add a call to saveAuthInfo. With this call, we are simply storing the userId and token properties.
- (void)viewDidAppear:(BOOL)animated { MSClient *client = self.todoService.client; if (client.currentUser != nil) { return; } [client loginWithProvider:@"facebook" controller:self animated:YES completion:^(MSUser *user, NSError *error) { [self saveAuthInfo]; [self refresh]; }]; }
- Now that we've seen how we can cache the user token and ID, let's see how we can load that when the app starts. In theviewDidLoad method in QSTodoListViewController.m, add a call to loadAuthInfo, after self.todoService has been initialized.
- (void)viewDidLoad { [super viewDidLoad]; // Create the todoService - this creates the Mobile Service client inside the wrapped service self.todoService = [QSTodoService defaultService]; [self loadAuthInfo]; // Set the busy method UIActivityIndicatorView *indicator = self.activityIndicator; self.todoService.busyUpdate = ^(BOOL busy) { if (busy) { [indicator startAnimating]; } else { [indicator stopAnimating]; } }; // have refresh control reload all data from server [self.refreshControl addTarget:self action:@selector(onRefresh:) forControlEvents:UIControlEventValueChanged]; // load the data [self refresh]; }
- If the app makes a request to your Mobile Service that should get through because the user is authenticated and you receive a 401 response (unauthorized error), it means the user token you're passing over has expired. In the completion handler for every method that we have that interacts with our Mobile Service, we could check for a 401 response, or we can handle things in one place: the MSFilter's handleRequest method.
Source fromhttp://azure.microsoft.com/en-us/documentation/articles/mobile-services-ios-get-started-users/
No comments :
Post a Comment