I'm trying to inject session cookies I've acquired separately into a WKWebview request, which turns out to be quite a pain...
I managed to inject the session cookies using this solution, as follows:
// Acquiring the cookies
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: s.request!.url!)
//Appending all the cookies into one raw string.
var cookiesRawString = ""
for c in cookies {
cookiesRawString += "\(c.name)=\(c.value); "
}
var req: URLRequest = try! URLRequest(url: URL, method: method)
// Then the injection itself
request.setValue(cookiesRawString, forHTTPHeaderField: "Cookie")
webView.load(req)
Let me quickly explain the server logic with pseudo code:
Server receive call to endpoint /endpoint1 with initial session cookies appended
It then proceed to redirect the client to /endpoint2 with user generated token appended in the url.
requesting the second endpoint with token appended results in the final redirect to /endpoint3 with Set-Cookie header containing one time session cookies
/endpoint3 with the one time session cookies appended results in 200 response, and the user is recognized.
The problem is that for some reason the when I append the cookies to the initial request using the method above, it results with a redirect loop, while on the Android platform it works flawless (I used there a similar injection method).
The only difference that I saw between them was that the android app injected the cookies only on the initial request, and all the subsequent redirect calls were without those session cookies.
While the ios repeated the initial session cookies on all the redirect calls (even ignoring the server set-cookie header and appending the initial session cookies..).
Am I doing something wrong? How can I make the wkwebview use the injected cookies only on the initial request?
Edit 1: Also tried falling back to UIWebview, but it produces the same results, it seems that injecting the cookies as a header is not good, but I tried using HTTPCookieStorage, but it won't save the cookies!
// the count is 7
var cookiesCount = HTTPCookieStorage.shared.cookies(for: s.request!.url!)?.count
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headers, for: s.request!.url!)
for c in cookies {
HTTPCookieStorage.shared.setCookie(c)
}
// Count is still 7!
cookiesCount = HTTPCookieStorage.shared.cookies(for: s.request!.url!)?.count
Edit 2:
Well I found out the UIWebview is using a global instance of the cookie storage, the same as alamofire (which I've used to fetch the session cookies), so there was no need to add the cookies manually, the site recognized the user.
But I still prefer to use WKWebview, as the UIWebview memory leak sky rockets (over 100 mb after couple of web pages navigation!).
Is there a way to use the global cookie jar (used by alamofire) in WKWebview??
I think this might be unrelated, but i had a similar issue.
The reason was the modified cookie was messing up all my subsequent request using NSURL.sharedSession. It turns out the cookie set using WKWebView was wiping out the headers from NSURLSession.sharedSession. I think the cookie storage is shared across multiple sessions. So, i ended up using EphemeralSession, instead of sharedSession.
I managed to get it working on WKWebview, using a hackish solution:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction:
WKNavigationAction, decisionHandler:
#escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url!.absoluteString
if UserAppendix.isLogin && url != previousNavigateUrl {
previousNavigateUrl = url
if url.contains("/endpoint1") {
let headerFields = navigationAction.request.allHTTPHeaderFields
let headerIsPresent = headerFields!.keys.contains("Cookie")
if headerIsPresent {
decisionHandler(WKNavigationActionPolicy.allow)
} else {
var req = URLRequest(url: navigationAction.request.url!)
let cookies = NetworkAppendix.httpSessionCookies
let values = HTTPCookie.requestHeaderFields(with: cookies)
req.allHTTPHeaderFields = values
webView.load(req)
decisionHandler(WKNavigationActionPolicy.cancel)
}
}
else if firstTime {
firstTime = false
let req = URLRequest(url: navigationAction.request.url!)
webView.load(req)
decisionHandler(WKNavigationActionPolicy.cancel)
}
else {
decisionHandler(.allow)
}
}
else {
decisionHandler(.allow)
}
}
I set the cookies on the first request, and on the second request break the flow and create a new request (with the redirect url), to avoid the session cookies I set on the first request, all subsequent requests are treated the same.
I know it's not perfect, but it gets the job done.
Related
I am loading a url on webview, in which user will have to login. I am making a request by following way:
let urlStr = "https://flex-showcase.bloxcms.com/business/guebert-food-and-family-a-must-for-sundays-in-april/article_94462124-fbd4-5d0b-9841-880d82844c05.html"
var req = URLRequest(url: URL(string: urlStr)!)
req.addValue("1", forHTTPHeaderField: "X-Townnews-Now-API-Version")
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let userAgent = appdelegate.appUserAgent
appdelegate.webviewObj.customUserAgent = userAgent
appdelegate.webviewObj.load(req)
after login we have seen that user session does not maintain properly. as we have seen that "X-Townnews-Now-API-Version" on all HTTP transactions is missing after login. Also I have observed that:
1) After reloading the webpage again every think works fine.
2) Also backend debugged that "login buttons are doing XHR, clicking on the sign-in button should have no bearing on HTTP requests. HTTP requests need to be intercepted at the webkit level and pass the right headers on all HTTP transactions."
I have webView in which I load some url. I need to set custom header for that URLRequest. For the first request it works as expected, header is received on server side and content is displayed accordingly. However if I open another link from displayed page, headers are lost and request is sent without header.
My lucky guess is that, header is added only for the first time and I have to add it every time when request to load url is sent. However I couldn't find method where can I do so.
Currently I'm setting header in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
let url = URL(string: "https://mywebsite.com");
var requestobj = URLRequest(url: url!);
requestobj.addValue("my_request_id", forHTTPHeaderField: "X-Requested-With");
myWebView.loadRequest(requestobj);
}
Am I missing something or should I add header in different place for every request?
Yes, you should add custom headers each time when you create request.
Ok, thanks to iphonic, to pointing at shouldStartLoadWith. I could use that to understand is request new or old one and solve my problem by doing so:
func webView(_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebViewNavigationType) -> Bool{
if(navigationType == UIWebViewNavigationType.linkClicked)
{
var req = request;
req.addValue("my_request_id", forHTTPHeaderField: "X-Requested-With");
self.myWebView.loadRequest(req);
return false;
}
else {
return true;
}
}
So here I check, if navigation type is clickedLink, then I don't load current request, instead I copy it, reapply custom header and load it into myWebView.
If navigationType isn't linkClicked, I proceed request without changes.
I need the user to be able to log out. When they log in now, a cookie gets saved automatically, that works fine. But I want to clear all cookies.
NSURLCache.sharedURLCache().removeAllCachedResponses()
This does not work
You can remove all the cookies specifically stored for an URL like this (Swift 3):
let cstorage = HTTPCookieStorage.shared
if let cookies = cstorage.cookies(for: url) {
for cookie in cookies {
cstorage.deleteCookie(cookie)
}
}
What I want to do is create an NSURLSession that does not automatically give a value to the Cookie HTTP header when I'm making an NSMutableURLRequest, because I set that value on my own. However, I want to be able to store the cookie that comes back to me when I make a sign in API request.
I use the following code to instantiate my session:
func createSession() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
// Set cookie policies.
configuration.HTTPCookieAcceptPolicy = .Always
configuration.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
configuration.HTTPShouldSetCookies = false
// ...
return NSURLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
}
When the NSURLSessionDataTask comes back to me in its completionHandler, I dig into the shared cookie storage to get the cookies that came with the response. However, I always get an empty array.
if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(response.URL!) {
println("cookies: \(cookies)") // Prints an empty array.
if let cookie = cookies.last as? NSHTTPCookie {
// I save the cookie to disk here.
}
}
Why is this happening even when I've set the NSURLSession to always accept cookies, and even provided a cookie storage?
I can only get the behavior that I want by setting the HTTPShouldSetCookies to true and supplying a Cookie HTTP header in my NSMutableURLRequest anyway. However, the Apple documentation on HTTPShouldSetCookies says that I should set it to false if I were to provide the cookie on my own in the request level:
If you want to provide cookies yourself, set this value to NO and provide a Cookie header either through the session’s HTTPAdditionalHeaders property or on a per-request level using a custom NSURLRequest object.
Technologies: iOS8, SWIFT, XCode 6
Using swift, what is the best way to save an external website's html/css/js, modify that saved data with my own css / js, and then load it in the view. This way, the external page loads with my custom styles/js already implemented.
I'm not sure how complicated your use of the UIWebView is but, the quickest implementation I can think of (aside from the evaluateJS route you've already done):
Create a property to decide if a request has been hijacked yet (by you).
var hijacked = false
provide the UIWebViewDelegate protocol method.
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//if true it must be our version, reset hijack and allow to load
if hijacked {
hijacked = false
return true
}
//original request. Don't let it load, instead trigger manual loader.
else {
hijacked = true
manuallyLoadPage(request)
return false
}
}
Then you just need a method to fetch the page, get the text, manipulate the text, and then load the page with your version.
func manuallyLoadPage(request: NSURLRequest) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
var html = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
html = html.stringByReplacingOccurrencesOfString("</head>", withString: "<script>alert(\"I added this\")</script></head>", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
self.webView.loadHTMLString(html, baseURL: response.URL!)
}
task.resume()
}
This is just a quick and dirty approach, you may want to do a more thorough job of tracking which requests are hijacked requests etc... This one just assumes an even odd kind of approach. You could obviously manipulate the html however you want, I just added the JS alert as a proof of concept.