Moya: Create AuthPlugin to send json on network request is not work

Created on 6 Apr 2017  路  7Comments  路  Source: Moya/Moya

Hi guys,

I try to send json(username and password) on network requests.

{ 
  "username": "me",
  "password": "1234"
}

Following the documentation:
https://github.com/Moya/Moya/blob/circle-ci-xcode-8-3/docs/Examples/AuthPlugin.md

the func prepare() can be used to add jwt to requests.

The problem is that this function is not being called and therefore the parameters that are passed inside json do not work.

Any idea? Or, what is missing .. if I am doing something wrong. Or what I understand does not make sense? 馃槄

struct AuthUserPlugin: PluginType {

    let username: String
    let password: String

    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        var request = request
        let json = try? JSONSerialization.data(withJSONObject: ["username": username, "password": password], options: JSONSerialization.WritingOptions.prettyPrinted)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = json
        return request
    }

    // MARK: plugin

    func willSendRequest(_ request: RequestType, target: TargetType) {
        logger.debug("send request: \(request.request?.url?.absoluteString ?? String())")
    }

    func didReceiveResponse(_ result: Result<Moya.Response, Moya.Error>, target: TargetType) {
        switch result {
        case .success(let response):
            if 200..<400 ~= (response.statusCode)  {
                logger.debug("\n-->\nReceiving response: (\(response.statusCode )) de \(response.response?.url?.absoluteString ?? String()) \n Data --> \n \(response.data).\n")
            }

        case .failure(let error):
            logger.debug("\n-->\nConnection error: \(error)\n")
        }
    }
}
let provider = RxMoyaProvider<MyTarget>(plugins: [AuthUserPlugin(username: username, password: password)])
question

All 7 comments

@douglastaquary Was wondering what your workaround was. Thanks!

@rlam3 This implementation does not work. Do you have any idea how I can send these parameters in the body of the request as json with Moya? On my implementation the parameters are nil. :(

The function prepare() is not called. Any suggestion?

@douglastaquary I've been trying to replicate this. Can you share any more information? I've set breakpoints on prepare() and it's called for me.

@douglastaquary I didn't use AuthPlugin yet. However I would suggest that you use the pass parameters in the headers. There is a method where we can add the parameters into the header. My problem revolves more around how do I refresh an expired jwt token per request which I was hoping I could learn something from your implementation. hahaha.

@rlam3 I think that know what you're talking about.. My first implementation was like this. But also not work. : / This method where we can add the parameters into the header can to work also to pass json in body of request?
Are you have any code for show me?

I solved the problem in the simplest and obvious way I think. I only implemented Moya's default code. After a long time trying to implement in other ways, I realized that this is the most simple and objective way. As we speak here in Brazil: Moya is Top! 馃帀

I updated the Moya version of 8.0.0-beta.3 to 8.0.3 and

enum MyAPI {
    case xAuth(username: String, password: String)
}

 var parameters: [String: Any]? {
        switch self {
        case .xAuth(let username, let password):
            return ["username": username as AnyObject,
                    "password": password as AnyObject]
        default:
            return nil
        }
    }

    var parameterEncoding: Moya.ParameterEncoding {
        switch self {
        case .xAuth:
            return JSONEncoding.default
        default:
            return URLEncoding.default
        }
    }

 let provider =  RxMoyaProvider<MyAPI>(plugins: [NetworkLoggerPlugin(verbose: true)])

The result is this json with username and password in the request body. 馃嵑

{ 
  "username": "me",
  "password": "1234"
}

Very easy! 馃憦

Hey @douglastaquary thanks for sharing your solution, this may be useful for others as well!

Cheers from Brazil 馃槈

Was this page helpful?
0 / 5 - 0 ratings