JSON NSURLRequest with credentials - ios

I have an api in my swift app that needs some extra authorization. There are some examples provided by the service but none in swift.
My Code:
let request = NSURLRequest(URL: NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev")!)
Example in Python
import urllib2
request = urllib2.Request("https://www.kimonolabs.com/api/au4sl00w? apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev", headers={"authorization" : "Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx"})
contents = urllib2.urlopen(request).read()
Example in Ruby
require 'rest_client'
response = RestClient.get('https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev', {'authorization' => 'Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx'});
print(response);
Example in R
library('RCurl')
library('rjson')
json <- getURL('https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWuc',
httpheader = c(authorization='Bearer A5ve02gq40itf0eoYfT5ny6drZwcysxx'))
obj <- fromJSON(json)
print(obj)
So, how can I do this in Swift?

Modified answer from: "How to make an HTTP request + basic auth in Swift".
I believe it would look something like this (and assuming your API_ID is au4sl00w) :
let token = "yourToken"
// create the request
let url = NSURL(string: "https://www.kimonolabs.com/api/au4sl00w?apikey=iFotcJDm95fB6Ua7XiZRDZA0jl3uYWev")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
And be sure to create a new access token, now that this one is public :)

Related

iOS - pipe file to HTTP request

I'm trying to upload a large (like in don't fit in memory) file to S3 using presigned request. I finally got it to work with curl
curl -v -T video.mp4 "http://<myBucket>.s3.amazonaws.com/video.mp4?AWSAccessKeyId=<myAccessKey>&Expires=1492187347&Signature=vpcUnvGALlVXju31Qk2nXNmBTgc%3D"
I'm trying to now do that from my app. I first tried with AF (that I'd rather not use):
let videoPath = Bundle.main.path(forResource: "media", ofType: "mov")!
let videoUrl = URL(fileURLWithPath: videoPath)
let presignedUrl = "http://<myBucket>.s3.amazonaws.com/video.mp4?AWSAccessKeyId=<myAccessKey>&Expires=1492187347&Signature=vpcUnvGALlVXju31Qk2nXNmBTgc%3D"
request = Alamofire.upload(videoUrl, to: presignedUrl, method: .put, headers: [:])
request.responseString(completionHandler: { response in
print(response)
})
request.resume()
Which prints an successful response that is actually an error:
The request signature we calculated does not match the signature you provided. Check your key and signing method.
I've read in a few places that there might be issues with headers, and I'd rather not use AF here anyway.
What is in Swift an equivalent of curl -T filePath url ?
When signing the request, pass the content type. In node:
var AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: 'us-east-1',
});
var s3 = new AWS.S3();
var params = {
Bucket: bucketName,
Key: 'path/my-video.mp4',
Expires: 1800000,
ContentType: 'video/mp4',
};
var signedUrl = s3.getSignedUrl('putObject', params)
// returns something like:
// https://<- my bucket ->.s3.amazonaws.com/path/my-video.mp4?AWSAccessKeyId=<- my access key ->&Content-Type=video%2Fmp4&Expires=1492203291&Signature=HeRBUObYQiQ6FIH%2Fg%2FOI0qv57VY%3D
and now in swift:
let request = NSMutableURLRequest(url: presignedUrl)
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.httpMethod = "PUT"
request.setValue("video/mp4", forHTTPHeaderField: "Content-Type")
request.setValue("<- my bucket ->.s3.amazonaws.com", forHTTPHeaderField: "host")
let uploadTask = session.uploadTask(with: request as URLRequest, fromFile: videoUrl) { data, response, error in
...
}
uploadTask.resume()

"HTTP Status 400 - Bad Request - The request sent by the client was syntactically incorrect"?

I've done a http request with post parameters so many times, and I have now so many of them working just fine, I don't know why this one is not
this is the code
let url = NSURL(string: "bla bla lba")
let request = NSMutableURLRequest(URL: url)
let body = "id=\(requestClient!.id!)"
print("body = \(body)")
request.HTTPBody = body.dataUsingEncoding(NSASCIIStringEncoding)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
let session = NSURLSession.sharedSession()
let task1 = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
the server expects a form parameter named id and its value is long
when I print the id from swift (as you can see the code), I get this
id=1453045943881.0
and i get this error
HTTP Status 400 - Bad Request - The request sent by the client was syntactically incorrect.
sounds like the server said the request is not correct, but where is the wrong?
this is the server
#Path("/checkForResponses")
#POST
public Response checkForResponeses (#FormParam("id") long id) {

Differences between Using NSJSONSerialization.dataWithJSONObject and dataUsingEncoding to make up the HTTP body in Swift

I have seen two kinds of methods to make up the HTTP body.
First one is:
let url = NSURL(string: "http://example.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let postString = "id=13&name=Jack"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
Second one is:
let url = NSURL(string: "http://example.com")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let params = ["id":"13", "name":"Jack"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
When I directly print out the request.HTTPBody the data is different. So I am wondering are there any differences between these two methods in terms of the implementation of the server side? Assuming I'am using PHP.
there're two format data.
in code using postString.dataUsingEncoding it will send data in urlencoded format. In client you must set request's Content-Type header to "application/x-www-form-urlencoded" or something like "application/x-www-form-urlencoded charset=utf-8"
in code using NSJSONSerialization.dataWithJSONObject it will send data in json format. In client you must set request's Content-Type header field to "application/json"
I'm iOS dev so I don't know about format's effect to server side PHP. to answer your question you must find difference between application/x-www-form-urlencoded and application/json format in server side

How to set HTTPBody?

In Swift I'm trying to make a post request (using the NSURLSession) to sign in a user to a WebAPI web services.
The Url is www.myurltest.com/Token and I must pass the following string as POST body:
grant_type=password&username=MyUsername&password=MyPassword.
So in Swift I've make:
let session = NSURLSession.sharedSession();
let url = NSURL(string:"www.myurltest.com/Token");
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
Now I want to set the POST body (that is a string) but I don't know how:
request.HTTPBody = ?????
Thanks.
You're almost there, you just need to turn the string into an NSData object. If your string is in a variable named body, your code will look like request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)

iOS Missing grant_type

I'm getting {"error_description":"Missing grant_type parameter value","error":"invalid_request"} when trying to request access token for the first time. My code is below:
let params : [String : String] =
["client_id" : clientID,
"client_secret" : secret,
"redirect_uri" : redirectURL,
"code" : code,
"grantType" : "authorization_code"
]
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("aapplication/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("\(request.HTTPBody!.length)", forHTTPHeaderField: "Content-Length")
What might be the problem? Thank you in advance.
Wow, I don't want to sound harsh, but there are multiple issues with this code.
You are not sending grant_type, but you do send grantType.
You are encoding the post body as application/json, but you are setting the Content-Type to be aapplication/x-www-form-urlencoded which seems to be a misspelling of application/x-www-form-urlencoded.
So two possible spelling issues and a content type mismatch.
Work out if you need to send application/x-www-form-urlencoded or application/json. Format the data and set the content type as needed.
Double check the spelling of everything.

Resources