How to Create a Ntlm Authentication Header to Use with Alamofire

How can I use Alamofire to add auth header to each request, and do something if the response is 401?

As per to your requirement, I would personally prefer to have a intermediate class for calling methods of Alamofire.

For that you can add auth header on each web service call.

Here is the following example for Intermediate class.

  • WebClient.swift

    class WebClient: SessionManager {

    static let sharedManager = WebClient()

    func responseRequest(_ url: String, method: Alamofire.HTTPMethod, parameter: Parameters? = nil, encoding: ParameterEncoding, header: HTTPHeaders? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Void {

    self.request(url, method: method, parameters: parameter, encoding: encoding, headers: header).response { response in
    completionHandler(response)
    }

    } }

You can modify above class as per requirement or you can directly pass header in request method for each webservice call.

Authorization Header not setting in Alamofire 5?

After setting the Authorization header in your URLRequest:

urlRequest.addValue("\(APIConstants.API.token.rawValue) \(token.key)", forHTTPHeaderField: "Authorization")

then you override all the request's headers by setting headers property:

urlRequest.headers = headers

A nice solution would be to update the headers that you already created above, like this:

var headers: HTTPHeaders = [
.contentType(APIConstants.ContentType.json.rawValue),
.accept(APIConstants.ContentType.json.rawValue),
]

if let token = token {
headers.add(.authorization("\(APIConstants.API.token.rawValue) \(token.key)"))
}

urlRequest.headers = headers

Basic auth header in Alamofire

let user = "your username"

let password = "your password"

let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!

let base64Credentials = credentialData.base64EncodedString()

let headers = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]

//put slash before \ (base64Credentials)

Alamofire.request("place your url", method: .get, parameters: nil,encoding: URLEncoding.default, headers: headers) .responseJSON { response in
switch response.result {
case .success(_):
//your success code
}
case .failure(_):
//your failure code
}
}

How to add authorization on header using Swift 3.0 + Alamofire 4.0

Use Authorization as your header key.

However, you shouldn't need to do it, considering HTTP header keys are case-insensitive, the issue is probably on the server.



Related Topics



Leave a reply



Submit