JWT Request Made but It tells that request does not contain access token

I tried to make a Request with JWT Authorization, The server is Using Python/Flask-Restful. The API Works on Postman, so I guess there must be something wrong with my IOS Code. The server returns an error shows that

"Authorization Required. Request does not contain an access token",

I`m making the request from IOS Using following code.

func GetUserData(username: String, accesstoken: String,completion: @escaping (_ result: UserDataModel) -> Void){
    let url = URL(string: "http://********/****/\(****)")
    var request = URLRequest(url: url!)
    request.httpMethod = "GET"
    request.addValue("Authorization", forHTTPHeaderField: accesstoken)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response as? HTTPURLResponse{
            if response.statusCode != 200 {
                print("Server Error When Update User Data")
            } else {
                if let data = data {
                    do {
                        ******
                        completion(Data)
                    }
                    catch {
                        print(error)
                    }
                }
            }
        }
        }.resume()
    }

I have no idea What is going on, Any help?

1 answer

  • answered 2018-07-11 03:19 Bailey Parker

    It looks like you're adding the header:

    Bearer base64junk: Authorization
    

    When instead you want:

    Authorization: Bearer base64junk
    

    You just have the parameters to addValue(_:forHTTPHeaderField:) backwards. You want this instead:

    request.addValue(accesstoken, forHTTPHeaderField: "Authorization")
    

    This should be obvious if you read that line of code like an English sentence ("value authorization for header field access token"?). In the future, you could also use something like Charles Web proxy to intercept your requests and verify that they are indeed formed the way you expect.