Environment: Swift 3 and Moya 8.0.1 and RxSwift.
Goal: I'm attempting to call a rest API that requires base64 encoded basic authentication.
I've attempted to use the CredentialsPlugin + URLCredential and pass the username/password but the rest API returned 401 (unauthorized). I wasn't able to determine if there's an option in that plugin to base64 encode the login credentials.
I can achieve this functionality using the Swift 3 URLSessionConfiguration + URLRequest objects by setting an HTTP request header that looks like this: "Authorization" : "Basic
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
I found a solution/work-a-round by adding a headers property to my TargetType extension and then returning an endpointClosure when initializing my provider.
I still think the CredentialsPlugin should have a configurable option to support base64 encoded login credentials.
I had to create a custom plugin to support basic auth. I might do a pull request to add this to Moya when I have time:
struct BasicAuthenticationPlugin: PluginType {
let key: String
func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
let encodedKey = key.utf8Encoded.base64EncodedString(options: [])
var request = request
request.addValue("Basic " + encodedKey, forHTTPHeaderField: "Authorization")
return request
}
}
@yar1vn Check AccessTokenPlugin
@SeRG1k17 it didn't provide such functionality. thats why I am here too. Thanks @yar1vn, this solution works.
@ARGAMX back in the day we didn't support basic authentication, but since few releases the AccessTokenPlugin is capable of supporting both basic and bearer and custom types (e.g. JWT).
Most helpful comment
I had to create a custom plugin to support basic auth. I might do a pull request to add this to Moya when I have time: