Introduction to LinkedIn API Authentication for iOS Apps
As a developer, creating applications that integrate with the LinkedIn platform can be a valuable addition to your portfolio. However, to do so, you need to navigate the complex world of authentication and permissions. In this article, we will delve into the process of setting up LinkedIn API authentication for iOS apps using the OAuth Starter Kit.
Background: Understanding OAuth
OAuth is an authorization framework that enables applications to access resources on behalf of a user without sharing their credentials. It works by granting the application limited access to the user’s data, allowing it to perform specific actions on their behalf.
In the context of LinkedIn API authentication, OAuth serves as the foundation for securing your app’s interactions with the platform. By using OAuth, you can ensure that users are only authorized to access specific features and data within your app.
The OAuth Flow
The OAuth flow is a standardized process used by OAuth clients (your iOS app) to obtain an access token from an authorization server (LinkedIn). The flow consists of several steps:
- Client Registration: Your app registers with LinkedIn as a client, providing essential information such as the app’s name and description.
- Redirect URI: You specify a redirect URI that will be used to route users back to your app after they authorize access.
- Authorization Request: Your app redirects the user to LinkedIn’s authorization endpoint, where they can choose to grant or deny access.
- Authorization Code: If the user grants access, LinkedIn redirects the user back to your specified redirect URI with an authorization code in the URL query parameter.
- Token Exchange: You exchange the authorization code for an access token by sending a POST request to LinkedIn’s token endpoint.
Setting Up LinkedIn API Authentication
To set up LinkedIn API authentication for your iOS app, you will need to follow these steps:
Step 1: Register Your App with LinkedIn
First, you’ll need to register your app with LinkedIn. To do this, follow these steps:
- Go to the LinkedIn Developer Platform and create an account if you haven’t already.
- Click on “Create a new application” and fill in the required information about your app, including its name, description, and redirect URI.
- Save and submit your registration.
Step 2: Set Up OAuth Starter Kit
The OAuth Starter Kit is a pre-built implementation of the OAuth flow that you can use to authenticate users in your iOS app. To set up the OAuth Starter Kit:
- Install the LinkedIn SDK for iOS using CocoaPods or manual installation.
- Import the
LSOAuthclass and initialize it with your client ID, client secret, and redirect URI.
Here’s an example of how to initialize the OAuth Starter Kit:
import LinkedInSDK
class OAuthManager {
let clientId = "YOUR_CLIENT_ID"
let clientSecret = "YOUR_CLIENT_SECRET"
let redirectUri = "YOUR_REDIRECT_URI"
func initOAuth() {
// Initialize the OAuth starter kit with your client ID, client secret, and redirect URI.
let oauth = LSOAuth(clientId: self.clientId, clientSecret: self.clientSecret, redirectUri: self.redirectUri)
oauth.startAuthorization()
}
}
Step 3: Handle User Authentication
Once you’ve initialized the OAuth Starter Kit, you can handle user authentication using the LSOAuth class. When a user grants access to your app, LinkedIn will redirect them back to your specified redirect URI with an authorization code in the URL query parameter.
To handle this redirect and obtain an access token:
- Implement a handler function that responds to URL requests.
- Use the
LSOAuthclass to exchange the authorization code for an access token.
Here’s an example of how to implement a handler function using Swift:
import UIKit
class OAuthHandler: NSObject, UIViewControllerDelegate {
let oauth = LSOAuth(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", redirectUri: "YOUR_REDIRECT_URI")
var accessToken: String?
func handleAuthorizationCode(code: String) {
// Handle the authorization code and exchange it for an access token.
let url = URL(string: "https://api.linkedin.com/oauth/v2/accessToken")!
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy)
request.httpMethod = "POST"
request.httpBody = "{\"grant_type\":\"authorization_code\",\"code\":\"\(code)\",\"redirect_uri\":\"YOUR_REDIRECT_URI\"}".data(using: .utf8)!
request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
// Handle the access token and save it securely.
if let error = error {
print("Error exchanging authorization code: \(error)")
} else if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
let accessToken = (json as? [String: String])?["access_token"] ?? ""
self?.accessToken = accessToken
print("Access token: \(accessToken)")
} catch {
print("Error parsing JSON: \(error)")
}
}
}
task.resume()
}
func urlForRedirect() -> URL {
return URL(string: "YOUR_REDIRECT_URI")!
}
}
Handling API Requests
Once you’ve obtained an access token, you can use it to authenticate API requests. To do this:
- Create a new instance of the
LSOAuthclass and initialize it with your client ID, client secret, and redirect URI. - Use the
LSOAuthclass to send an API request to LinkedIn.
Here’s an example of how to send a GET request using Swift:
import LinkedInSDK
class APIManager {
let oauth = LSOAuth(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", redirectUri: "YOUR_REDIRECT_URI")
func getProfiles() -> [LinkedInProfile] {
// Create a new instance of the LSOAuth class and initialize it with your client ID, client secret, and redirect URI.
let auth = oauth.authenticatedRequest()
let url = URL(string: "https://api.linkedin.com/v2/people/?projection=(id)")[0]
// Set the request headers to include the access token in the Authorization header.
auth.setValue("Bearer \(oauth.accessToken)", forHTTPHeaderField: "Authorization")
auth.setValue("application/json", forHTTPHeaderField: "Content-Type")
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy)
request.httpMethod = "GET"
task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
// Handle the API response and parse it into a JSON array.
if let error = error {
print("Error sending GET request: \(error)")
} else if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
return json as! [Dictionary<String, String>]
} catch {
print("Error parsing JSON: \(error)")
}
}
}
task.resume()
}
func createProfile(name: String, email: String) -> Bool {
// Create a new instance of the LSOAuth class and initialize it with your client ID, client secret, and redirect URI.
let auth = oauth.authenticatedRequest()
let url = URL(string: "https://api.linkedin.com/v2/people/")[0]
// Set the request headers to include the access token in the Authorization header.
auth.setValue("Bearer \(oauth.accessToken)", forHTTPHeaderField: "Authorization")
auth.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy)
request.httpMethod = "POST"
request.httpBody = "{\"name\":\"\(name)\",\"email\":\"\(email)\"}".data(using: .utf8)!
task = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
// Handle the API response and parse it into a JSON array.
if let error = error {
print("Error sending POST request: \(error)")
} else if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
return true
} catch {
print("Error parsing JSON: \(error)")
}
}
}
task.resume()
}
}
Conclusion
In this tutorial, we’ve covered the basics of integrating LinkedIn OAuth with Swift and iOS. We’ve walked through the process of handling user authentication, exchanging authorization codes for access tokens, and sending API requests to LinkedIn.
While this is just a basic example, you can customize it to fit your specific needs and use cases. Remember to always handle errors securely and save sensitive data securely.
Last modified on 2023-06-18