Tutorial: Call a protected web API in iOS (Swift) app

This is the fourth tutorial in the tutorial series that guides you on signing in users and calling a protected web API using Microsoft Entra ID.

In this tutorial, you:

  • Call a protected web API.

Prerequisites

Call API

Once you have a token, your app can use it in the HTTP header to make an authorized request to the Microsoft Graph:

header key value
Authorization Bearer <access-token>

Add the following code to the ViewController class:

    func getContentWithToken() {

        // Specify the Graph API endpoint
        let graphURI = getGraphEndpoint()
        let url = URL(string: graphURI)
        var request = URLRequest(url: url!)

        // Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
        request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization")

        URLSession.shared.dataTask(with: request) { data, response, error in

            if let error = error {
                self.updateLogging(text: "Couldn't get graph result: \(error)")
                return
            }

            guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {

                self.updateLogging(text: "Couldn't deserialize result JSON")
                return
            }

            self.updateLogging(text: "Result from Graph: \(result))")

            }.resume()
    }

See Microsoft Graph API to learn more about the Microsoft Graph API.

Test your app

Build and deploy the app to a test device or simulator. You should be able to sign in and get tokens for Microsoft Entra ID accounts.

The first time a user signs into your app, they'll be prompted by Microsoft identity to consent to the permissions requested. While most users are capable of consenting, some Microsoft Entra tenants have disabled user consent, which requires admins to consent on behalf of all users. To support this scenario, register your app's scopes.

After you sign in, the app will display the data returned from the Microsoft Graph /me endpoint.

Next steps

Learn more about building mobile apps that call protected web APIs in our multi-part scenario series.