URLRequest cookies are always empty - ios

When trying to retrieve the cookies from anywhere I can't parse the cookies. The storage seems to be always empty. Maybe I'm just fundamentally misunderstanding the whole thing.
I start off by doing a get or post request against my endpoint via a shared URLSession task (for example: https://httpbin.com/cookies)
If I get a valid response status I try to parse the cookies (Note that response is not nil and everything works fine here, I just didn't include that code because i don't think its relevant):
func setCookies(response: URLResponse) {
let response = response as! HTTPURLResponse
let cookies = HTTPCookie.cookies(withResponseHeaderFields:response.allHeaderFields as! [String : String], for: response.url!)
print("cookies: \(cookies) \(HTTPCookieStorage.shared.cookies!)")
}
For both of these methods my result is always empty.
Even though the header fields are set:
I already did set cookieAcceptPolicy to .alwaysand httpShouldHandleCookies to true
Is there something else I'm missing? How is it possible for both of them to be empty?

Related

HTTP DELETE Works From Browser But Not From Postman or IOS App

When attempting an http request to my rest api, I continually get a 401 error when using the following code. I don not get this error making any other type of request. I have provided the function that makes the request below.
func deleteEvent(id: Int){
eventUrl.append(String(id))
let request = NSMutableURLRequest(url: NSURL(string: eventUrl)! as URL)
request.httpMethod = "DELETE"
print(eventUrl)
eventUrl.removeLast()
print(self.token!)
request.allHTTPHeaderFields = ["Authorization": "Token \(self.token)"]
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
if error != nil {
print("error=\(String(describing: error))")
//put variable that triggers error try again view here
return
}
print("response = \(String(describing: response))")
}
task.resume()
}
When sending the delete request with postman, the rest api just returns the data I want to delete but does not delete it. For reference I have posted the view and permissions classes associated with this request Any help understanding why this may be resulting in an error is greatly appreciated!
Views.py
class UserProfileFeedViewSet(viewsets.ModelViewSet):
"""Handles creating, reading and updating profile feed items"""
authentication_classes = (TokenAuthentication,)
serializer_class = serializers.ProfileFeedItemSerializer
queryset = models.ProfileFeedItem.objects.all()
permission_classes = (permissions.UpdateOwnStatus, IsAuthenticated)
def perform_create(self, serializer):
"""Sets the user profile to the logged in user"""
#
serializer.save(user_profile=self.request.user)
Permissions.py
class UpdateOwnStatus(permissions.BasePermission):
"""Allow users to update their own status"""
def has_object_permission(self, request, view, obj):
"""Check the user is trying to update their own status"""
if request.method in permissions.SAFE_METHODS:
return True
return obj.user_profile.id == request.user.id
HEADER SENT WITH DELETE REQUEST VIA POSTMAN
Preface: You leave out too much relevant information from the question for it to be properly answered. Your Swift code looks, and please don't be offended, a bit beginner-ish or as if it had been migrated from Objective-C without much experience.
I don't know why POSTMAN fails, but I see some red flags in the Swift code you might want to look into to figure out why your iOS app fails.
I first noticed that eventUrl seems to be a String property of the type that contains the deleteEvent function. You mutate it by appending the event id, construct a URL from it (weirdly, see below), then mutate it back again. While this in itself is not necessarily wrong, it might open the doors for racing conditions depending how your app works overall.
More importantly: Does your eventUrl end in a "/"? I assume your DELETE endpoint is of the form https://somedomain.com/some/path/<id>, right? Now if eventUrl just contains https://somedomain.com/some/path your code constructs https://somedomain.com/some/path<id>. The last dash is missing, which definitely throws your backend off (how I cannot say, as that depends how the path is resolved in your server app).
It's hard to say what else is going from from the iOS app, but other than this potential pitfall I'd really recommend using proper Swift types where possible. Here's a cleaned up version of your method, hopefully that helps you a bit when debugging:
func deleteEvent(id: Int) {
guard let baseUrl = URL(string: eventUrl), let token = token else {
// add more error handling code here and/or put a breakpoint here to inspect
print("Could not create proper eventUrl or token is nil!")
return
}
let deletionUrl = baseUrl.appendingPathComponent("\(id)")
print("Deletion URL with appended id: \(deletionUrl.absoluteString)")
var request = URLRequest(url: deletionUrl)
request.httpMethod = "DELETE"
print(token) // ensure this is correct
request.allHTTPHeaderFields = ["Authorization": "Token \(token)"]
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Encountered network error: \(error)")
return
}
if let httpResponse = response as? HTTPURLResponse {
// this is basically also debugging code
print("Endpoint responded with status: \(httpResponse.statusCode)")
print(" with headers:\n\(httpResponse.allHeaderFields)")
}
// Debug output of the data:
if let data = data {
let payloadAsSimpleString = String(data: data, encoding: .utf8) ?? "(can't parse payload)"
print("Response contains payload\n\(payloadAsSimpleString)")
}
}
task.resume()
}
This is obviously still limited in terms of error handling, etc., but a little more swifty and contains more console output that will hopefully be helpful.
The last important thing is that you have to ensure iOS does not simply block your request due to Apple Transport Security: Make sure your plist has the expected entries if needed (see also here for a quick intro).

400 error when downloading file with "Authorization" header

The server returning a json file that is:
{"ctrl":{"code":400,"text":"Not valid Access token","ts":"2020-03-05T11:54:01.547Z"}}
Code:
public func startDownload(url: URL, pathURL: URL) {
let accessToken: String! = "Bearer \(Constants.access_token)"
self.dirURL = pathURL
var request = URLRequest(url: url)
guard let token = accessToken else { return }
request.addValue(token, forHTTPHeaderField: "Authorization")
downloadTask = backgroundSession.downloadTask(with: request)
downloadTask.resume()
}
FYI: access token is valid, it is working with Postman.
You're going to have a problem because, unfortunatelly, there's no good solution to this issue. Authorization is one of the Reserved HTTP Headers and setting it either in URLRequest header, or in URLSessionConfiguration.httpAdditionalHeaders may simply not work:
If you set a value for one of these reserved headers, the system may ignore the value you set, or overwrite it with its own value, or simply not send it.
One might expect you could provide this token in URLSessionTaskDelegate method urlSession(_:task:didReceive:completionHandler:) which handles authentication challenges, but in there you need to provide a URLCredential object, and sadly it doesn't have a constructor that takes a Bearer token, so that's a no-go.
So basically, short of writing your own URLProtocol implementation, your best bet would be to send the token in some additional, custom, header field and have the server grab it from there (if you have control over server code). Source

NSURLCache using cache for requests older than max-age

I've been banging my head against the while now trying to figure out what's going on with NSURLCache.
Basically, the server I am connecting to doesn't set any cache control headers... So following various guides and apple docs (ie https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Concepts/CachePolicies.html) I set my own cache control headers in the willCacheResponse delegate and then return that modified response in the completion handler. The apple docs and the resource I've read seem to indicate this should work. But what I'm seeing is that the cached data is returned after it should be expired based on max-age. It seems like max-age is being ignored and the NSURLCache is using another heuristic to determine if it should pull data from the cache or not.
I set the max-age=60 cache-control header and I've verified using Charles that the data is pulled from cache and no network requests are made long after 60 seconds. Eventually (seems non-deterministic) a new request will be made that actually goes to the server (usually after a few hours have passed and I try the request again).
Here is the code, for testing purposes I'm just hardcoding the max-age to 60 seconds:
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: #escaping (CachedURLResponse?) -> Void) {
var modifiedReponse: URLResponse? = nil
if let HTTPResponse = proposedResponse.response as? HTTPURLResponse {
if var newHeaders = HTTPResponse.allHeaderFields as? [String : String] {
if newHeaders["Cache-Control"] == nil {
newHeaders["Cache-Control"] = "max-age=60"
}
modifiedReponse = HTTPURLResponse(url: HTTPResponse.url!, statusCode: HTTPResponse.statusCode, httpVersion: "HTTP/1.1", headerFields: newHeaders)
}
}
let response = modifiedReponse ?? proposedResponse.response
var newCachedResponse: CachedURLResponse? = nil
newCachedResponse = CachedURLResponse(response: response, data: proposedResponse.data, storagePolicy: proposedResponse.storagePolicy)
}
There are a few optional checks in there but I have confirmed that the response on newCachedResponse I am returning has the cache control header set to max-age=60. Am I doing something obviously wrong here? Or is NSURLCache just F'd?
I know this is super late, but I think you just need to pass that newCachedResponse back into the completion handler closure provided to you.
Such as the last line being:
completionHandler(newCachedResponse)

How can I pull the grades on the website, and perform the login using a POST request?

I am trying to pull my school grades from the website which stores all my grades, but I am having trouble logging in using HTTP requests, and pulling the information of the next page. Any help is appreciated :)
override func viewDidLoad() {
super.viewDidLoad()
let myUrl = NSURL(string: "https://homeaccess.katyisd.org/HomeAccess/Account/LogOn?ReturnUrl=%2fhomeaccess%2f")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "User_Name=**hidden**&Password=**hidden**"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data,response,error in
if(error != nil){
print("error=\(error)")
return
}
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let’s convert response sent from a server side script to a NSDictionary object:
do{
var myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
var firstNameValue = parseJSON["User_Name"] as? String
print("firstNameValue: \(firstNameValue)")
}
}catch{
print(error)
}
}
}
First, you need task.resume() after defining the task in order to start the connection loading, otherwise the object will be created and nothing will actually happen.
According to this error you posted, there's an SSL verification error on the site you are trying to access. The most secure option is to fix the SSL on the site, but I presume that is beyond your control in this case. The easier fix is to bypass the SSL error by adding "App Transport Security Settings" > "Allow Arbitrary Loads" = YES in your info.plist, as #André suggested. Or, if you are only using the one domain, bypass the particular domain in the NSExceptionDomains. See this question for more info.
According to this error you posted, a JSON parsing error is occurring. It is currently being caught and printed by your catch block, so the data is not actually processed. In your case, this is occurring because the response from Home Access Center is HTML, not JSON, so the JSON parser is failing. You are probably looking for an HTML parser. Swift does not have one built-in; look at this question for some example open-source options.
I have actually created a program that interfaces with Home Access Center. Sadly, there is no public API available -- APIs typically return JSON, which is easier to work with. Instead, you will need to use an HTML parser to analyze the page that is meant for human users and cookies to fake that a human user is logging on.
add task.resume() at the end of your code. also add the following to your info.plist file:

How can I get data out of NSURLRequest config object

I have an Angular web build inside an iOS app and want to POST requests up to the native layer with some JSON that I can use to build some native functionality. I am using the old UIWebView (because Angular) so am using an NSURLProtocol to intercept the request. This works and I can break at the point that the request comes in. The problem is that I can not see the JSON in the data property at this point because it is not the response. The request is still in the config object but I have no idea how to grab this.
My angular code for creating the post is currently like this:
var newdata = $.param({
json: JSON.stringify({
name: "Lee"
})
});
$http.post(url, newdata)
and in my NSURLProtocol class I am successfully intercepting this POST in this method but the HTTPBody property is nil:
override class func canInitWithRequest(request:NSURLRequest) -> Bool {
if (request.URL!.absoluteString as NSString).containsString("request_media_gallery") {
if(request.HTTPBody != nil){
let data:NSData = request.HTTPBody!
print(data)
}
return true
}
return request.URL?.host == "file"
}
If I debug this in chrome I get a 405 because of CORS but I can see that my request object does not have any data but does have a config object. Here's the console log from Chrome:
By the time a URL request gets down to the protocol layer, IIRC, the URL Loading System sanitizes it in a lot of ways. In particular, if a request has an HTTPBody object associated with it, it basically does this:
req.HTTPBodyStream = [NSInputStream inputStreamWithData:req.HTTPBody];
req.HTTPBody = nil;
As a result, to get the data, you need to read from the HTTPBodyStream, regardless of whether the request was originally created with an NSData object or a body stream.

Resources