3
votes

I am trying to make posts to my Wordpress blog via Swift. I am using the Wordpress REST API with Java Web Token (JWT) authentication. The first step is to pass the user credentials to the server using the HTTP POST method. The server then returns a JSON Object containing the JWT token needed for authentication. I can get this all working using a REST API program like Postman, but I am having trouble with the Swift code.

My credentials are sent just fine and the server returns some data, but I am having trouble getting the token from this data.

This Swift code was generated by the Postman app:

import Foundation

let headers = [
  "Content-Type": "application/json",
  "cache-control": "no-cache",
]
let parameters = [
  "username": "myUsername",
  "password": "myPassword"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://myDomain/wp-json/jwt-auth/v1/token")! as URL,
                                    cachePolicy: .useProtocolCachePolicy,
                                timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

When I do the HTTP POST command in Postman I get back this JSON:

{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvY3F1aWNrLmNhIiwiaWF0IjoxNTQ3Njc3MDMzLCJuYmYiOjE1NDc2NzcwMzMsImV4cCI6MTU0ODI4MTgzMywiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMyJ9fX0.DgxmmSFKnEdXuWi5EiBk1BpFvWrD57KIE8TiWazId-4",
"user_email": "myEmail",
"user_nicename": "myUsername",
"user_display_name": "myUsername"
}

Is there anyway to get this same result using Swift? I imagine that this is being returned by the session.dataTask method, I just have no idea how to parse it.

2

2 Answers

2
votes

Okay, so the answer was to add this to the session.dataTask method (in the else closure).

let jsonObject = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
            let query = jsonObject["token"] as! String
            print(query)
0
votes

I know this is an old post but I'm trying to use my JWT-AUTH REST API with WordPress in Swift as well. I have achieved acquiring a token, however, I'd like to know how to use it to access certain protected pages? ie: my website.com/user-page/USERNAME where USERNAME is the name of the user and it only provides access to tis page if the user is logged in with that username.

I tried throwing in the token as a BearerToken in postman but no luck!