授权 Header 未在 Alamofire 5 中设置?

Authorization Header not setting in Alamofire 5?

我正在将基本身份验证令牌设置到我的 URLRequest 并使用 Alamofire 来执行。

我设置了 3 headers,content、accept 和 auth...content 和 accept 在网络流量中可见,但 auth 不可见。如果我在发送之前打印 URLRequest 的 headers 就可用...

有什么想法吗?因为我看不到它如何在发布前删除身份验证 header

代码如下:

        // Construct url
        let url = try APIConstants.baseUrl.asURL()

        // Append path
        var urlRequest = URLRequest(url: url.appendingPathComponent(path))

        // Determine HTTP method
        urlRequest.httpMethod = method.rawValue

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

        if let token = token {
            urlRequest.addValue("\(APIConstants.API.token.rawValue) \(token.key)",
                                forHTTPHeaderField: "Authorization")
        }

        urlRequest.headers = headers

        // Add http body to request
        if let parameters = parameters {
            do {
                let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
                urlRequest.httpBody = data
            } catch (_) {
                print("APIRouter: Failed to parse body into request.")
            }
        }

        //Encoding
        let encoding: ParameterEncoding = {
            switch method {
            case .get:
                return URLEncoding.default
            default:
                return JSONEncoding.default
            }
        }()

        return try encoding.encode(urlRequest, with: parameters)

    }

在我的休息客户端中,我这样执行:

        return Observable<T>.create { observer in
            let request = AF.request(urlConvertible).responseDecodable { (response: DataResponse<T, AFError>) in
                switch response.result {
                case .success(let value):
                    observer.onNext(value)
                    observer.onCompleted()
                case .failure(let error):
                    switch response.response?.statusCode {
                    case 403:
                        observer.onError(APIError.forbidden)
                    case 404:
                        observer.onError(APIError.notFound)
                    case 409:
                        observer.onError(APIError.conflict)
                    case 500:
                        observer.onError(APIError.internalServerError)
                    default:
                        observer.onError(error)
                    }
                }
            }

            return Disposables.create {
                request.cancel()
            }
        }
    }

编辑:

更新函数以显示更多问题:

    func asURLRequest() throws -> URLRequest {
        // Construct url
        let url = try APIConstants.baseUrl.asURL()

        // Append path
        var urlRequest = URLRequest(url: url.appendingPathComponent(path))

        // Determine HTTP method
        urlRequest.httpMethod = method.rawValue

        let headers: HTTPHeaders = [
            .contentType(APIConstants.ContentType.json.rawValue),
            .accept(APIConstants.ContentType.json.rawValue),
            .authorization("Token a5555485aa251b28fdsfasdfdsb379c131fddad")
        ]

        urlRequest.headers = headers

        // Add http body to request
        if let parameters = parameters {
            do {
                let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
                urlRequest.httpBody = data
            } catch (_) {
                print("APIRouter: Failed to parse body into request.")
            }
        }

        //Encoding
        let encoding: ParameterEncoding = {
            switch method {
            case .get:
                return URLEncoding.default
            default:
                return JSONEncoding.default
            }
        }()

        return try encoding.encode(urlRequest, with: parameters)

    }

URLRequest 中设置 授权 header 后:

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

然后通过设置 headers 属性:

覆盖所有请求的 header
urlRequest.headers = headers

一个不错的解决方案是更新您在上面创建的 headers,如下所示:

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

另一种解决方案是使用键值对,如下所示:

var header: HTTPHeaders = [:]
        
if let token = getValueFromUserDefaults(keyName: "authToken") as? String {
                
    header["Authorization"] = token
                
}
            

我一直用这个方法。对我来说更方便。