OneDrive resumable upload in iOS - nsurlsession

I'm having issue with resumable upload, using URLSession in iOS.
Everything works, except the resumable upload.
The session upload creation works, I've got my uploadUrl back, so I simply start an URLSessionUploadTask:
let url = URL(string: urlUploadString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "PUT"
urlRequest.setValue("bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let task = urlsession.uploadTask(with: urlRequest, fromFile: localFile)
task.resume()
The transfer goes through, however, in the end, I receive a http code 400 with the response:
["error": {
code = invalidRequest;
message = "Invalid Content-Range header value";
}]
The thing, I can't set the Content-Range header per chunk, because iOS handles the upload, not me. And it doesn't seem to set Content-Range header automatically for each chunk sent.

Related

Malformed request from aiohttp.ClientSession().post() with multiple image files

I'm still relatively new to Python and my first time to use aiohttp so I'm hoping someone can help spot where my problem is.
I have a function that does the following:
retrieves from the JSON payload two base64 strings - base64Front and base64Back
decode them, save to "images" folder
send the Front.jpg and Back.jpg to an external API
this external API expects a multipart/form-data
imgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())
The response I'm getting is status code 400 with:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}
If I call the url via Postman and send the two jpg files, I get status code 200.
Hope someone can help here.
Thanks in advance.
Try using FormData to construct your request. Remove the content type from header and use it in FormData field as below:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)
Reference: https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file

Calling rest server from mobile app

Following on from https://lists.hyperledger.org/g/composer/message/91
I have adapted the methodology described by Caroline Church in my IOS app.
Again I can authenticate with google but still get a 401 authorization error when POSTing.
I have added the withCredentials parameter to the http header in my POST request.
does the rest server pass back the token in cookie ? I don't receive anything back from the rest server.
where does the withCredentials get the credentials from ?
COMPOSER_PROVIDERS as follows
COMPOSER_PROVIDERS='{
"google": {
"provider": "google",
"module": "passport-google-oauth2",
"clientID": "93505970627.apps.googleusercontent.com",
"clientSecret": "",
"authPath": "/auth/google",
"callbackURL": "/auth/google/callback",
"scope": "https://www.googleapis.com/auth/plus.login",
"successRedirect": "myAuth://",
"failureRedirect": "/"
}
}'
the successRedirect points back to my App. After successfully authenticating I return to the App.
Got this working now. The App first authenticates with google then exchanges the authorization code with the rest server.
The Rest server COMPOSER_PROVIDERS needs to be changed to relate back to the app.
clientID is the apps ID in google,
callbackURL and successRedirect are reversed_clientID://
The App calls http://localhost:3000/auth/google/callback with the authorization code as a parameter.
this call will fail, but an access_token cookie is written back containing the access token required for the rest server.
The user id of the logged in user is not passed back, when exchanging the code for a token with google we get back a JWT with the details of the logged in user. We need this back from the rest server as well as the token. Is there any way to get this ?
changing the COMPOSER_PROVIDERS means that the explorer interface to the Rest server no longer works.
func getRestToken(code: String) {
let tokenURL = "http://localhost:3000/auth/google/callback?code=" + code
let url = URL(string:tokenURL);
var request = URLRequest(url: url!);
request.httpMethod = "GET";
request.setValue("localhost:3000", forHTTPHeaderField: "Host");
request.setValue("text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8", forHTTPHeaderField: "Accept");
request.setValue("1", forHTTPHeaderField: "Upgrade-Insecure-Requests");
request.httpShouldHandleCookies = true;
request.httpShouldUsePipelining = true;
let session = URLSession.init(configuration: .default);
session.configuration.httpCookieAcceptPolicy = .always;
session.configuration.httpShouldSetCookies=true;
session.configuration.httpCookieStorage = HTTPCookieStorage.shared;
let task = session.dataTask(with: request) { (data, response, error) in
var authCookie: HTTPCookie? = nil;
let sharedCookieStorage = HTTPCookieStorage.shared.cookies;
// test for access_token
for cookie in sharedCookieStorage! {
if cookie.name == "access_token"
{
print(“Received access token”)
}
}
guard error == nil else {
print("HTTP request failed \(error?.localizedDescription ?? "ERROR")")
return
}
guard let response = response as? HTTPURLResponse else {
print("Non-HTTP response")
return
}
guard let data = data else {
print("HTTP response data is empty")
return
}
if response.statusCode != 200 {
// server replied with an error
let responseText: String? = String(data: data, encoding: String.Encoding.utf8)
if response.statusCode == 401 {
// "401 Unauthorized" generally indicates there is an issue with the authorization
print("Error 401");
} else {
print("HTTP: \(response.statusCode), Response: \(responseText ?? "RESPONSE_TEXT")")
}
return
}
}
task.resume()
}
have you authorised the redirect URI in your Google OAUTH2 configuration ?
This determines where the API server redirects the user, after the user completes the authorization flow. The value must exactly match one of the redirect_uri values listed for your project in the API Console. Note that the http or https scheme, case, and trailing slash ('/') must all match.
This is an example of an Angular 5 successfully using it Angular 5, httpclient ignores set cookie in post in particular the answer at the bottom
Scope controls the set of resources and operations that an access token permits. During the access-token request, your application sends one or more values in the scope parameter.
see https://developers.google.com/identity/protocols/OAuth2
The withCredentials option is set, in order to create a cookie, to pass the authentication token, to the REST server.
Finally this resource may help you https://hackernoon.com/adding-oauth2-to-mobile-android-and-ios-clients-using-the-appauth-sdk-f8562f90ecff

Download file with AJAX using Dart

Is it at all possible to download a file upon an ajax request?
Does it matter if it's same domain / cross domain?
I know it can be done upon redirecting the browser to a URL and setting relevant headers, but was wondering if it can be done when doing an ajax request.
I'm POSTing JSON as the Request Payload to a URL and based on the content of the JSON, I want to send back a specific file.
client.post(url, body: request, headers:{"Content-Type":"application/json"}).then((res) {
if (res.statusCode == 200) {
if ("application/json" == res.headers["content-type"]) {
// parse JSON here
} else {
// download the content if Content-Disposition is set
}
}
}).whenComplete(() {
client.close();
}).catchError((exception, stacktrace) {
print(exception);
print(stacktrace);
showErrorMessage("An Error Occurred");
});
I can see the the correct headers coming back for downloading a PDF, but it's not doing anything if I receive these headers via an AJAX response.
Update - clarifying:
If you click this link, it will do a GET request to Github and download the file: https://github.com/dartsim/dart/archive/master.zip
I'm trying to download the file using a POST request via Dart's BrowserClient.post.

AFNetworking and Authorization Header

I'm new to AFNetworking, and I'm trying to use it to talk to an API that I've written in Go. I'm having difficulty getting the Authorization header to work. I've subclassed AFHTTPSessionManager and configured it as follows
+ (HMAPIClient *)sharedHMAPIClient
{
static HMAPIClient* _sharedHMAPIClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedHMAPIClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:HMBaseURL]];
});
return _sharedHMAPIClient;
}
- (instancetype)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (self) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.requestSerializer = [AFJSONRequestSerializer serializer];
[self.requestSerializer setAuthorizationHeaderFieldWithUsername:RegistrationAPIKey
password:#"Doesn't matter what goes here."];
}
return self;
}
- (void)hitTestEndpoint
{
[self GET:#"testEndpoint" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#", error);
}];
}
When I call -(void)hitTestEndpoint, I see the following headers in my server logs (Authorization is missing):
Key: Accept-Encoding Value: [gzip, deflate]
Key: Connection Value: [keep-alive]
Key: Accept-Language Value: [en;q=1]
Key: User-Agent Value: [TestApp/2 (iPad Simulator; iOS 8.1; Scale/2.00)]
Key: Accept Value: [*/*]
For comparison, when I hit the same endpoint with the following curl command,
curl https://api.example.com/v1/testEndpoint/ -u test_xqzwjcasogptbnpa:
I see the following headers:
Key: Authorization Value: [Basic eHF6d2pjYXNvZ3B0Ym5wYTo=]
Key: User-Agent Value: [curl/7.30.0]
Key: Accept Value: [*/*]
Can someone point me in the right direction? -Thanks
Update:
I have added AFNetworkActivityLogger so that I can see each request. The Authorization header is indeed included. Also, I tried hitting http://headers.jsontest.com, which returns the HTTP request headers received from the client. The Authorization header is present in that output.
So, the problem must be with my server. I'm already logging all headers for each request, and I'm not sure where else to look. Going to tag this question with Go to see if someone has an idea.
Update 2:
I added a call to httputil.DumpRequest at the top of my request handler, and it also shows that the Authorization header is missing. By the way, any custom headers that I set do appear as expected. It's just the Authorization header that's missing.
Here's the Go Code:
func testResponse(rw http.ResponseWriter, request *http.Request) {
// check output from DumpRequest()
dump,err := httputil.DumpRequest(request,true)
check(err)
fmt.Println("Output of DumpRequest():")
fmt.Println(string(dump))
fmt.Println("============")
fmt.Println("request.Headers:")
for key, value := range request.Header {
fmt.Println("Key:", key, "Value:", value)
}
fmt.Println("===============")
// return some dummy JSON
rw.Header().Set("Content-Type", "application/json")
rw.Write(PersonToJson(getPerson("2f6251b8-d7c4-400f-a91f-51e09b8bfaf4")))
}
The server log you're showing looks like the headers after Go has already parsed them. It would be helpful to see the raw, plaintext HTTP headers that Go received. That would tell you if Go is ignoring the header or if something upstream is stripping it out.
Edit: Not sure why Go would strip out the Authorization header before giving you the supposedly raw request. But I think the Authorization header is normally sent by the client only after making a previous un-authorized request and getting a 401 response from the server with a WWW-Authenticate header. Since it sounds like your client is sending the Authorization header out of the blue, maybe the Go server API is ignoring & stripping the header because it never asked the client to send it.
If you just want to send a simple auth token on every request, what if you simply used a made up X- header instead, since you indicated that other headers you set arrive just fine?

Facebook graph api: upload multipart/form-data encoded image

I am trying to post an image using the source parameter (Multipart/form-data) in the Graph API explorer. My source parameter looks like this:
{Content-Type: multipart/form-data; boundary=xxxsrixxx
--xxxsrixxx
Content-Disposition: attachment; filename=try2.gif
Content-Type: image/gif
Content-Transfer-Encoding: binary,base64
R0lGODlhXgExAYeAAQAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBk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oLAARKACLaQDDDwMLG+67ze677+68Ae7MI+7MRe7MZ+7Mie7Mq+7Mze7M7+7NAe7dKOKAAAIf8LUElBTllHSUYxLjAWSW1hZ2UgZnJvbSBjbGlwYm9hcmQBIAA7
--xxxsrixxx--}
This always seems to return
{
"error": {
"message": "(#324) Requires upload file",
"type": "OAuthException",
"code": 324
}
}
Few questions:
Does facebook source parameter accept base64 encoded image data?
Has anyone tried using the source parameter in the graph api explorer and have a working sample?
should the source param value should be url-encoded?
Note: My access token has all the required permissions and if i am not wrong, my encoding seems to be wrong. The base64 encoded text above is a complete image and i could decode it and get the image.
Ok. This is going to sound crazy. After a week of trying I was able to post an image successfully to the facebook wall. The fix was to send the raw binary data as it is (no base64 encoding - fb does not like it) and make sure your multipart/form-data is correct. For instance, if you boundary is defined as "boundary=--xxxsrixxx" your actual request should look like this "----xxxsrixxx\r\nContent-Disposition......\r\n----xxxsrixxx"
This works fine for me, it only uses native JavaScript features and a file input:
const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];
fileReader.onloadend = async () => {
const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
const formData = new FormData();
formData.append('access_token', pageAccessToken);
formData.append('source', photoData);
formData.append('message', 'some status message');
let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
body: formData,
method: 'post'
});
response = await response.json();
console.log(response);
};
fileReader.readAsArrayBuffer(file);
More information: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/

Resources