Alamofire clear all cookies - ios

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)
}
}

Related

iOS Swift WKWebView Maintain User after login at app level

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."

Save userDefault token after Login

I am new in software and I have a question.
I have LoginPage called LoginVC(screenshot as below).When the user opened the app first time, if the member login with his username and password or via Facebook account, next time he opened the app he will pass the login screen and show the "NewsVC" directly. If he logged out, he will see the Login Page again.
According to my investigations I must use UserDefault method and create a local database(for example SQLite). Probably it creates a access token for the entered users. But I don't know how I will do. Maybe there is the question about this problem in this site but because of I don't know in a detailed manner couldn't find the topic.
Can you explain this topic and share an example with a simple Swift 3 code.
Thanks in advance
LoginVC ScreenShot
Securitywise, it is considered a bad practice to store login tokens in UserDefaults, I'd suggest using Keychain API instead.
"Hackers" can relatively easy read data from UserDefaults and use your access token.
Keychain API is a bit hard to use, I'd suggest trying a 3rd party library, here is one example:
https://github.com/jrendel/SwiftKeychainWrapper
More info about securing your data on iOS:
https://github.com/felixgr/secure-ios-app-dev
If you are just learning - it is OK to use UserDefaults, but once you consider moving your app to production - refactor it to Keychain.
Try following Helper method
Set User ID
func setCurrentLoginID(_ struserid: String) {
UserDefaults.standard.set(struserid, forKey:"userID")
}
Check User Login or Not
func isUserLoggedIN() -> Bool {
let str = UserDefaults.standard.object(forKey: "userID") as! String
return str.characters.count > 0 ? true : false
}
Get User ID
func loggedUserId() -> String {
let str = UserDefaults.standard.object(forKey: "userID") as? String
return str == nil ? "" : str!
}
For Logout
func logout() {
UserDefaults.standard.set(nil, forKey: "userID")
}
Assuming you wanted to know how to implement this then you can store and get the value like below:-
let default = UserDefaults.standard
default.set(accessToken, forKey: "accessToken")
default.synchronized()
//Now get like this and use guard so that it will prevent your crash if value is nil.
guard let accessTokenValue = default.string(forKey: "accessToken") else {return}
print(accessTokenValue)

How to clear cache of safari in iOS app? [duplicate]

This question already has an answer here:
Alamofire clear all cookies
(1 answer)
Closed 6 years ago.
Please dont mark as Duplicate because I have tried all things but not working plz some one help me.
My app is having google sign in, while sign in I am getting all the previous signed-in accounts. How to remove those accounts?
Thank you in advance.
//MARK:- clear Cache
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
self.deleteCoreData()
GIDSignIn.sharedInstance().disconnect()
GIDSignIn.sharedInstance().signOut()
for cookie in HTTPCookieStorage.shared.cookies! {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
// Removes cache for all responses
URLCache.shared.removeAllCachedResponses()
Sorry, For duplicate question but I tried above code but its not working. Can please anyone guide me where am I wrong ?
Thank you again.
For Swift 3.0, clear all URL cache and cookies like this
URLCache.shared.removeAllCachedResponses()
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
Try to remove specific cookie, related to auth, e.g.:
var cookieProperties = [HTTPCookiePropertyKey:String]()
cookieProperties[.name] = "<cookie_name>"
cookieProperties[.domain] = "<domain>"
cookieProperties[.originURL] = "<origin_url>"
// <... etc ...>
if let cookie = HTTPCookie(properties: cookieProperties) {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
or just remove all cookies, if it's not a problem in your case:
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}

WKWebview injecting cookie header cause redirect loop

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.

Setting NSURLSessionConfiguration's HTTPShouldSetCookies to false disables cookie storage

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.

Resources