Browse Source

Added authorizationHeader API to generate base64 encoded authorization header.

This addresses the issue that the `Request.authenticate` function cannot be used to authenticate on servers that don’t send an authentication challenge.
Cédric Luthi 9 years ago
parent
commit
c2a282cc80
2 changed files with 47 additions and 0 deletions
  1. 16 0
      Source/Request.swift
  2. 31 0
      Tests/AuthenticationTests.swift

+ 16 - 0
Source/Request.swift

@@ -105,6 +105,22 @@ public class Request {
         return self
     }
 
+    /**
+        Returns a base64 encoded basic authentication credential as an authorization header dictionary.
+
+        - parameter user:     The user.
+        - parameter password: The password.
+
+        - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
+    */
+    public static func authorizationHeader(user user: String, password: String) -> [String: String] {
+        guard let data = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return [:] }
+
+        let credential = data.base64EncodedStringWithOptions([])
+
+        return ["Authorization": "Basic \(credential)"]
+    }
+
     // MARK: - Progress
 
     /**

+ 31 - 0
Tests/AuthenticationTests.swift

@@ -120,6 +120,37 @@ class BasicAuthenticationTestCase: AuthenticationTestCase {
         XCTAssertNotNil(data, "data should not be nil")
         XCTAssertNil(error, "error should be nil")
     }
+
+    func testHiddenHTTPBasicAuthentication() {
+        // Given
+        let authorizationHeader = Request.authorizationHeader(user: user, password: password)
+        let expectation = expectationWithDescription("\(URLString) 200")
+
+        var request: NSURLRequest?
+        var response: NSHTTPURLResponse?
+        var data: NSData?
+        var error: NSError?
+
+        // When
+        manager.request(.GET, "http://httpbin.org/hidden-basic-auth/\(user)/\(password)", headers: authorizationHeader)
+            .response { responseRequest, responseResponse, responseData, responseError in
+                request = responseRequest
+                response = responseResponse
+                data = responseData
+                error = responseError
+
+                expectation.fulfill()
+            }
+
+        waitForExpectationsWithTimeout(timeout, handler: nil)
+
+        // Then
+        XCTAssertNotNil(request, "request should not be nil")
+        XCTAssertNotNil(response, "response should not be nil")
+        XCTAssertEqual(response?.statusCode ?? 0, 200, "response status code should be 200")
+        XCTAssertNotNil(data, "data should not be nil")
+        XCTAssertNil(error, "error should be nil")
+    }
 }
 
 // MARK: -