Vaisakh Mohan
Vaisakh Mohan

Reputation: 77

Issue with sending bearer token in http header using urlsession in swift 3

I am sending bearer token in header using urlsession but I always get the result as unauthorized. I have seen the server log. I am getting body in there but not header.

    let key = UserDefaults.standard.object(forKey: "loginKey") as! String
        print(key)
        let url = NSURL(string: baseurl+"***")

        let request = NSMutableURLRequest(url: url! as URL)

        request.httpMethod = "GET"

        request.addValue("Bearer " + key, forHTTPHeaderField: "Authorization")
        let task = URLSession.shared.dataTask(with: request as URLRequest) 
{(data,response,error) -> Void in

        if error != nil
        {
          print(error?.localizedDescription as Any)
                        return
        }

       do 
       {
          let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

           print(json)
        }
      catch let error as NSError 
      {
         print(error.localizedDescription)
      }
    }
    task.resume()

I have also tried request.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")

Upvotes: 2

Views: 9070

Answers (1)

KKRocks
KKRocks

Reputation: 8322

Try this :

     var sessionConfig = URLSessionConfiguration.default
      var authValue: String? = "Bearer \(key)"
     sessionConfig.httpAdditionalHeaders = ["Authorization": authValue ?? <#default value#>]
     var session = URLSession(configuration: sessionConfig, delegate: self as? URLSessionDelegate, delegateQueue: nil)

Upvotes: 9

Related Questions