swiftrestkitura

Kitura TypeSafeHTTPBasic auth looking for credentials in post body?


I have a TypeSafe Codeable route in Kitura defined like this:

app.router.post("/games") { (auth: BasicAuth, respondWith: @escaping (Game?, RequestError?) -> ()) in 
    ...
}

But when I make a get request, I receive Could not decode received JSON: The required key 'id' not found.. This seems like the router is attempting to parse the auth object from the POST body rather than from the basic auth header. If I change the route to GET it works just fine, but I don't understand the Type Safe Codeable routing very well and I'm confused about what changed with the POST route. How do I get my BasicAuth to work the same with POST as with GET?


Solution

  • When using Kitura's Codable Routing, a POST handler expects to receive a Codable input from the message body. You can optionally specify one or more TypeSafeMiddleware requirements.

    If you want to perform a POST, you would want to match the post() function on Router that takes a Codable and a TypeSafeMiddleware as inputs:

    app.router.post("/games") { (auth: BasicAuth, input: MyInputType, respondWith: @escaping (Game?, RequestError?) -> ()) in 
        ...
    }
    

    What's happening in your case is that you are actually matching this post() function without TypeSafeMiddleware, where your auth type (which conforms to Codable) is being interpreted as your input type.

    If you do not expect to POST a payload to the server for this request, perhaps what you want instead is a GET which instead matches the get() function on Router that only takes a TypeSafeMiddleware as input:

    app.router.get("/games") { (auth: BasicAuth, respondWith: @escaping (Game?, RequestError?) -> ()) in 
        ...
    }
    

    Note that the TypeSafeMiddleware are the first parameter(s) to the route handlers, followed by any other input types (in the case of PUT or POST).