iOS Objective-C: Calling APIs

View on Github

iOS Objective-C: Calling APIs

Gravatar for martin.walsh@auth0.com
By Martin Walsh
Auth0

This tutorial will show you how to use Access Tokens to make authenticated API calls, using NSURLSession. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: CocoaPods 1.2.1 | Version 8.3.2 (8E2002) | iPhone 7 - iOS 10.3 (14E269)

Auth0 provides a set of tools for protecting your resources with end-to-end authentication in your application.

This tutorial shows you how to get an Access Token, attach it to a request with an authorization header and call an API. We recommend you use this method for the best security and compliance with RFC standards.

Before you continue with this tutorial, make sure that you have completed the previous tutorials. This tutorial assumes that:

  • You have completed the Session Handling tutorial and you know how to handle the Credentials object.
  • You have set up a backend application as API. To learn how to do it, follow one of the backend tutorials.

Create an Auth0 API

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API. You will use the identifier later when you're preparing the Web Authentication. For Signing Algorithm, select RS256.

Create API

Add a Scope

By default, the Access Token does not contain any authorization information. To limit access to your resources based on authorization, you must use scopes. Read more about scopes in the scopes documentation.

In the Auth0 dashboard, in the APIs section, click Scopes. Add any scopes you need to limit access to your API resources.

You can give any names to your scopes. A common pattern is <action>:<resource>. The example below uses the name read:messages for a scope.

create scope

Get the User's Access Token

To retrieve an Access Token that is authorized to access your API, you need to specify the API Identifier value you created in the Auth0 APIs Dashboard.

Present the Hosted Login Page:

// HomeViewController.m

HybridAuth *auth = [[HybridAuth alloc] init];
[auth showLoginWithScope:@"openid profile" connection:nil audience:"API_IDENTIFIER" callback:^(NSError * _Nullable error, A0Credentials * _Nullable credentials) {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (error) {
            NSLog(@"Error: %@", error);
        } else if (credentials) {
          // Do something with credentials such as save them.
          // Auth0 will dismiss itself automatically by default.
        }
    });
}];

Attach the Access Token

To give the authenticated user access to secured resources in your API, include the user's Access Token in the requests you send to the API.

Depending on the standards in your API, you configure the authorization header differently. The code below is just an example.

To attach an Access Token to a request:

// ProfileViewController.m

NSString* token = ... // The accessToken you stored after authentication
NSString *url = @"https://localhost/api"; // Set to your Protected API URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
// Configure your request here (method, body, and so on)

[request addValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    // Parse the response
}] resume];

Sample project configuration

When you are testing the sample project, configure your URL request in the ProfileViewController.swift file:

// ProfileViewController.m

NSString *url = @"https://localhost/api"; // Change to your API
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
// Configure your request here (method, body, and so on)

After you send a request and receive a response from your API, you can check the request status code in an alert view.

Read more about authentication API on the server-side in the API documentation.

Use Auth0 for FREE