I am coming from Java web development background and very new to Apache Cordova/PhoneGap development. I just started creating a small hybrid application which is using Ionic/Cordova.
I want to communicate with a REST end point and need to add a security token to http request header and also need to add the same value to a cookie as well. Since Asnyc request initiated by file system in mobile device, I can't add a cookie in JavaScript code. Simply because cross domain policy in web browsers not allowing writing cookies to other domains.
So to overcome this issue I have added few lines of code to viewControllerForRequest method in CDVViewController class (IOS platform plugin).
ObjectiveC Code as follows and simply it works. But I feel like it's a dirty way of fixing this issue and want to know the best approach to achieve my end goal.
Could be a Cordova plugin to intercept all http requests?
NSString* path = [[request URL] path];
if(path != nil) {
NSRange apiRequest = [path rangeOfString:@"secure/api" options:NSCaseInsensitiveSearch];
if (apiRequest.length > 0){
NSString* securityToken = [request valueForHTTPHeaderField:@"securityToken"];
if (securityToken != nil) {
NSString* host = [[request URL] host];
//add the secuirty token cookie to request
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"securityToken" forKey:NSHTTPCookieName];
[cookieProperties setObject:securityToken forKey:NSHTTPCookieValue];
[cookieProperties setObject:host forKey:NSHTTPCookieDomain];
[cookieProperties setObject:host forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}
}