Arnold Schmid
Arnold Schmid

Reputation: 163

How parse HTTPHeader in Swift

I would like to write a Swift script to authenticate against a Rest Server with digest authentication. I will not use URLSession, i would like to do it manually. I get an first response from the server like this one:

[
  ("Connection", "close"),
  ("Date", "Sun, 22 Dec 2019 07:36:50 GMT"),
  (
    "WWW-Authenticate",
    "Digest realm=\"Testserver\", domain=\"/\", nonce=\"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz\", algorithm=MD5, qop=\"auth\", stale=false"
  ),
  (
    "Cache-Control",
    "must-revalidate,no-cache,no-store"
  ),
  (
    "Content-Type",
    "text/plain;charset=utf-8"
  ),
  ("Content-Length", "16"),
  ("Server", "Jetty(9.4.19.v20190610)")
]

I get an object HTTPResponseHead in Swift. But how can I read the nonce or other part of the header. If I to call print (head.headers.contains(name: "nonce")) i get the result false. head is an object of HTTPResponseHead. Have I do manually parse the Header or there exists to read the header and then create my hashes for the authentication.

Upvotes: 1

Views: 666

Answers (1)

Nazmul Hasan
Nazmul Hasan

Reputation: 10590

Try with this method.

 func getAuthenticationKey(headerInfo: [(String, String)]) -> String?{
        for item in headerInfo.enumerated(){
            print("key: \(item.element.0), values : \(item.element.1)")

            let headerKeys = item.element.1.split(separator: ",")

            for item in headerKeys {
                if item.contains("nonce") {
                    let authinticationKey = item.split(separator: "=")[1]
                    return String(authinticationKey)
                }
            }

        }
        return nil
    }

USE:

 let headerInfo = [("Connection", "close"), ("Date", "Sun, 22 Dec 2019 07:36:50 GMT"), ("WWW-Authenticate", "Digest realm=\"Testserver\", domain=\"/\", nonce=\"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz\", algorithm=MD5, qop=\"auth\", stale=false"), ("Cache-Control", "must-revalidate,no-cache,no-store"), ("Content-Type", "text/plain;charset=utf-8"), ("Content-Length", "16"), ("Server", "Jetty(9.4.19.v20190610)")]
 print(getAuthenticationKey(headerInfo: headerInfo))

Output:

"KZN/eQFuVy7iONz+Mts27+nj2GwVMVSz"

Upvotes: 1

Related Questions