How do I handle authentication (Bearer, Basic, OAuth) in Swift?

Handling Authentication in Swift

In Swift, you can handle various authentication methods like Bearer, Basic, and OAuth by using URLSession along with custom headers for your requests. Below are examples of how to implement each authentication type.

Example: Basic Authentication

// Basic Authentication in Swift let username = "yourUsername" let password = "yourPassword" let loginString = "\(username):\(password)" let loginData = loginString.data(using: String.Encoding.utf8)! let base64LoginString = loginData.base64EncodedString() var request = URLRequest(url: URL(string: "https://api.example.com/auth")!) request.httpMethod = "GET" request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") let task = URLSession.shared.dataTask(with: request) { data, response, error in // Handle response here } task.resume()

Example: Bearer Token Authentication

// Bearer Token Authentication in Swift let token = "yourBearerToken" var request = URLRequest(url: URL(string: "https://api.example.com/data")!) request.httpMethod = "GET" request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let task = URLSession.shared.dataTask(with: request) { data, response, error in // Handle response here } task.resume()

Example: OAuth 2.0 Authentication

// OAuth 2.0 Authentication in Swift let token = "yourAccessToken" var request = URLRequest(url: URL(string: "https://api.example.com/secure-data")!) request.httpMethod = "GET" request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let task = URLSession.shared.dataTask(with: request) { data, response, error in // Handle response here } task.resume()

Bearer Authentication Basic Authentication OAuth Swift Swift URLSession Swift Networking