• Sales
  • My Account
  • Portal
Microsoft Azure Free trial
  • Features
    • What is Azure?
    • Compute

      Compute

      Virtual Machines
      Provision Windows and Linux Virtual Machines and applications in minutes
      Cloud Services
      Create highly available, infinitely scalable cloud applications and APIs
      Batch
      Run large-scale parallel and batch compute jobs
      RemoteApp
      Deploy Windows client apps in the cloud, run on any device

      Get credits that enable:

      4 Windows or Linux VMs

      24 x 7 for a month

      And much more...

      Learn more

    • Web & Mobile

      Web & Mobile

      Websites
      Deploy and scale web apps in seconds
      Mobile Services
      Build and host the backend for any mobile app
      API Management
      Publish APIs to developers, partners and employees securely and at scale
      Notification Hubs
      Scalable, cross-platform push notification infrastructure

      Get credits that enable:

      Deploy 20 websites

      over 10M mobile API calls

      And much more...

      Learn more

    • Data & Storage

      Data & Storage

      SQL Database
      Managed Relational SQL Database-as-a-service
      DocumentDB
      Managed NoSQL document database-as-a-service
      Redis Cache
      High throughput, low latency data access to build fast and scalable applications
      Storage
      Durable, highly available and massively scalable cloud storage
      StorSimple
      Hybrid cloud storage for enterprises, reduces costs and improves data security
      Azure Search
      Fully-managed search-as-a-service

      Get credits that enable:

      8 standard SQL Databases

      Hadoop instance for a week

      And much more...

      Learn more

    • Analytics

      Analytics

      HDInsight
      Provision managed Hadoop clusters
      Machine Learning
      Powerful cloud-based predictive analytics
      Stream Analytics
      Real-time stream processing
      Data Factory
      Orchestrate and manage data transformation and movement
      Event Hubs
      Ingest, persist, and process millions of events per second

      Get credits that enable:

      8 standard SQL Databases

      Hadoop instance for a week

      And much more...

      Learn more

    • Networking

      Networking

      Virtual Network
      Provision private networks, optionally connect to on-premises datacenters
      ExpressRoute
      Dedicated private network fiber connections to Azure
      Traffic Manager
      Load balance incoming traffic for high performance and availability

      Connect Virtual Machines with Virtual Network for free.

      Learn more

    • Media & CDN

      Media & CDN

      Media Services
      Encode, store, and stream video and audio at scale
      CDN
      Deliver content to end-users through a robust network of global data centers

      Get credits that enable:

      Encoding 100GB of media

      Transfer up to 1600GB of content

      And much more...

      Learn more

    • Hybrid Integration

      Hybrid Integration

      BizTalk Services
      Seamlessly integrate the enterprise and the cloud
      Service Bus
      Connect across private and public cloud environments
      Backup
      Simple and reliable server backup to the cloud
      Site Recovery
      Orchestrate protection and recovery of private clouds

      Get credits that enable:

      Send 200 million messages

      And much more...

      Learn more

    • Identity & Access Management

      Identity & Access Management

      Active Directory
      Synchronize on-premises directories and enable single sign-on
      Multi-Factor Authentication
      Safeguard access to your data and apps with an extra level of authentication

      Get credits that enable:

      Store 500,000 objects in Active Directory

      Multi-factor auth with 100 users

      And much more...

      Learn more

    • Developer Services

      Developer Services

      Visual Studio Online
      Plan, build and ship software, all from one place
      Application Insights
      Detect and solve problems to continuously improve web apps

      Each free account includes:

      Five free Basic licenses

      Unlimited private code repos

      And more!

      Learn more

    • Management

      Management

      Preview Portal
      Explore the new Azure Preview portal
      Scheduler
      Run your jobs on simple or complex recurring schedules
      Automation
      Simplify cloud management with process automation
      Operational Insights
      Collect, search and visualize machine data from on-premises and cloud
      Key Vault
      Safeguard and maintain control of keys and other secrets

      Sign-up for free and get $200 to spend on all Azure services

      Learn more

    • Case Studies
  • Pricing
  • Documentation
  • Downloads
  • Marketplace
  • Blog
  • Community
    • Service Updates
    • Training
    • Events
    • Partners
      • Partner opportunity
      • Grow your business
      • Build your offering
      • Get started
    • Education
    • Newsletter
  • Support
    • Support Options
    • Support Plans
    • Forums
    • Service Dashboard
    • Trust Center
      • Overview
      • Security
      • Privacy
      • Compliance
      • Resources
      • FAQ
    • Legal
      • Overview
      • Subscription Agreement
      • Services Terms
      • Offer Details
      • Privacy Statement
      • Service Level Agreements
      • Preview Supplemental Terms
      • Store Terms
      • Website Terms Of Use
    • FAQ
Tweet
Documentation
>
Mobile Services
>
iOS

Add authentication to your Mobile Services app

Updated:10/10/2014
Mobile Services, iOS
krisragh By krisragh and 9 contributors WAComPublishing brettburMSFT WalterHub mattchenderson mollybostic ggailey777 v-aljenk tysonn sdurandeu
Contribute to this article on GitHub

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:

  1. Register your app for authentication and configure Mobile Services
  2. Restrict table permissions to authenticated users
  3. Add authentication to the app
  4. 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.

  1. Log on to the Azure Management Portal, click Mobile Services, and then click your mobile service.

  2. 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.

  3. Choose a supported identity provider from the list below and follow the steps to register your app with that provider:

    • Microsoft Account
    • Facebook login
    • Twitter login
    • Google login
    • Azure Active Directory

    Remember to make a note of the client identity and secret values generated by the provider.

    IMPORTANT:

    The provider-generated secret is an important security credential. Do not share this secret with anyone or distribute it with your app.

  4. 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

  1. In the Management Portal, click the Data tab, and then click the TodoItem table.

  2. 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.

  1. In Xcode, open the project that you created when you completed the tutorial Get started with Mobile Services.

  2. 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

  1. Open the project file QSTodoListViewController.m and in the viewDidLoad method, remove the following code that reloads the data into the table:

    [self refresh];
    
  2. 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];
        }];
    }
    
    NOTE:

    If 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.

  3. 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.

  1. 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).

  2. 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"];
        }
    }
    
  3. 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];
        }];
    }
    
  4. 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 the viewDidLoad 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];
    }
    
  5. 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. To see how to handle this scenario, see this blog post

Next steps

In the next tutorial, Service-side authorization of Mobile Services users, you will take the user ID value provided by Mobile Services based on an authenticated user and use it to filter the data returned by Mobile Services.

Contribute to this article

Want to edit or suggest changes to this content? You can edit and submit changes to this article using GitHub.

Need more help using this Azure service? Go to an MSDN forum or StackOverflow discussion

  • Go Social
  • Facebook
  • Twitter
  • Rss
  • Newsletter
  • Microsoft Azure
  • Services
  • Regions
  • Case Studies
  • Pricing
  • Calculator
  • Documentation
  • Downloads
  • Marketplace
  • Microsoft Azure in China
  • Microsoft Azure Government
  • Community
  • Blogs
  • Service Updates
  • Forums
  • Events

  • Support
  • Forums
  • Service Dashboard
  • Support
  • Account
  • Subscriptions
  • Profile
  • Preview Features
  • Management Portal
  • Trust Center
  • Security
  • Privacy
  • Compliance
  • Hello from Seattle.
  • English (US)
    English (US) Čeština Dansk Deutsch
    English (India) English (UK) Español (ES) Suomi
    Français Ελληνικά Italiano Magyar
    Nederlands Bokmål Polski Português (BR)
    Português (PT) Svenska Română Türkçe
    Українська русский 日本語 한국어
    中文(简体) 中文(繁體)
     
  • USD
    US Dollar ($) Euro (€) Swiss Frank (chf) Argentine Peso ($)
    Australian Dollar ($) Danish Krone (kr) Canadian Dollar ($) Indonesian Rupiah (Rp)
    Japanese Yen (¥) Korean Won (₩) New Zealand Dollar ($) Norwegian Krone (kr)
    Russian Ruble (руб) Saudi Riyal (SR) South African Rand (R) Swedish Krona (kr)
    Taiwanese Dollar (NT$) Turkish Lira (TL) British Pound (£) Mexican Peso (MXN$)
    Malaysian Ringgit (RM$) Indian Rupee (₹) Hong Kong Dollar (HK$) Brazilian Real (R$)
     
  • Nutzungsbedingungen
  • Impressum
  • Contact Us
  • Trademarks
  • Privacy & Cookies
  • Feedback
Microsoft © 2015 Microsoft