Can I get cookies from Safari in a SFSafariViewController? - ios

tl;dr; see the question below
In my app, I have a login that uses SFSafariViewController and ASWebAuthenticationSession that follows the OAuth 2.0 flow (Using the AppAuth library).
The login works and the cookies are shared with Safari as expected. Thanks to the cookie sharing, users are automatically logged-in if they use the Safari app.
However, back in the app, if I launch a SFSafariViewController again, the cookies are missing. This surprises me, because I thought the cookie Store is the same for SFSafariViewController and Safari, and it clearly worked in the direction from SFSafariVC to the Safari app during login.
Is it intended not to work the other way round - from Safari to SFSafariViewController, or is it a bug?
I have not found clear statements in the documentation.
Of course I have not set ephemeral session to true, but according to the documentation it would do the opposite of what I want to achieve:
When not using an ephemeral session, all cookies except session cookies are available to the browser.
I've also found somehow related radars like http://www.openradar.me/33323462 and http://www.openradar.me/radar?id=5036182937272320 or this stackoverflow post: Why is SFSafariWebViewController not sharing cookies with Safari properly? but they do not answer my question.
According to this comment it could work if the cookies have an expiry date (set to a future date). I verified the cookies - they all have a future expiry date.
My question: Am I doing something wrong, or is this expected behaviour, that SFSafariViewController does not get cookies from an earlier SFSafariViewController instance in the same app or from Safari?

REQUIREMENTS
So it seems you want a solution to invoke secured web content from a mobile app, and to avoid an extra login. It is a common requirement and I will be adding some stuff to my blog on this topic over the next month or so.
STATE OF THE INDUSTRY
The problem with the above is that third party cookies, such as those issued by Identity Providers, are often dropped by default these days due to browser security initiatives such as Intelligent Tracking Prevention changes - which is ON by default in Safari:
COOKIE PROPERTIES
Worth checking that your cookies are issued with SameSite=None, which will give you the best options for a third party cookie based solution.
MOBILE FIRST DESIGNS
In an OAuth world, in order to meet the requirements, it is likely to be necessary to send a token from the mobile UI to the web UI, which of course has prerequisites that need to be designed for:
Web UI must use tokens
Web UI must use different strategies for token handling depending on the host
OPTION 1
One option is to use a mobile web view to show the web content - see my code below:
Web UI Code to ask the host for tokens
Mobile UI Code to service these requests
OPTION 2
Another option is to send something representing the token in a query string parameter from the mobile app to the Web UI, in which case you need to ensure that:
No usable tokens are recorded in web server logs
The token has a one time use only
A typical implementation would look like this:
Mobile UI calls an /api/token/encrypt endpoint
API stores a token hash in a database and returns an encrypted value with a short time to live
Token is sent from the Mobile App to the Web UI
Web UI calls an /api/token/decrypt endpoint to get the real token
The API's decrypt implementation deletes the database entry

Related

Django session cookie forgotten on every browser reopen - mobile Safari (iphone,ipad)

I wonder if anybody encountered with this problem. I am storing some data about visitor in django session. It works as expected but only mobile safari (iphone and ipad) have strange behaviour.
When I visit my site from iphone or ipad(Safari ver. 14.3) session cookie is normally set. But when I close the browser then reopen, new session cookie is generated.
This behaviour can be seen only on mobile safari version. I was not able to reproduce it on macOS desktop safari.
To solve this problem I had to change setup for session cookie in django settings.py:
SESSION_COOKIE_SAMESITE = ‘None’
According to django doc. cookie is normally set as ‘lax’ and this introduce security risk in my app.
SESSION_COOKIE_SAMESITE
Default: 'Lax' The value of the SameSite flag on the session cookie.
This flag prevents the cookie from being sent in cross-site requests
thus preventing CSRF attacks and making some methods of stealing
session cookie impossible. Possible values for the setting are:
'Strict': prevents the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a
regular link.

For example, for a GitHub-like website this would mean that if a
logged-in user follows a link to a private GitHub project posted on a
corporate discussion forum or email, GitHub will not receive the
session cookie and the user won’t be able to access the project. A
bank website, however, most likely doesn’t want to allow any
transactional pages to be linked from external sites so the 'Strict'
flag would be appropriate.
'Lax' (default): provides a balance between security and usability for websites that want to maintain user’s logged-in session after the
user arrives from an external link.

In the GitHub scenario, the session cookie would be allowed when
following a regular link from an external website and be blocked in
CSRF-prone request methods (e.g. POST).
'None' (string): the session cookie will be sent with all same-site and cross-site requests.
False: disables the flag.
I guess that I had to cause security hole in my django app intentionally. I don’t like it but I am not sure how serious risk it is. I would love to know why only mobile safari behave like that.

Configure browser cache in SFSafariViewController using Swift iOS

In my application I am implementing a feature where for some part I need to open my website using SFSafariViewController. For this I don't want the user to login again in the web application as well, so before I open the SFSafariViewController I want to pass some token, mail and other required information. So is this feasible and would allow me to use browser cache.
SFSafariViewController is very limited in what you can configure, as seen by the documentation: https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller. Apple intentionally keeps cookies and safari configuration separate from apps that are using it for security and privacy reasons.
I don't know if this is exactly what you're seeing, but I faced a similar issue where, if a user logged in via SFSafariViewControler, then logged out (not using SFSafariViewController), then logged in again, it wouldn't ask for a login/pass because it was still cached in the browser.
Pretty much the only 2 options for this are:
Have the logout flow take place within SFSafariViewController so that you can clear the cookies that way.
Apple has a new auth flow class ASWebAuthenticationSession (docs here) which has a new property you can set called prefersEphemeralWebBrowserSession which essentially opens the browser in private mode. This keeps any cookies from being stored in the browser. The only downside to this, is the prefersEphemeralWebBrowserSession property is only available in iOS 13+.
If this is the same issue you're facing and you can limit your app to iOS 13+, then I would suggest the ASWebAuthenticationSession route, otherwise you may need to find another solution.

WKWebview not syncronizing cookies after I log out of a domain, opened on it


I am developing a WKWebview app in swift. Here One needs to login to a specific domain. For this , I am throwing a cookie with logged in information/token.
But the problem occurs when I try to logout and the check if token exists?
And the token still exists even after logout.
Note - I checked on chrome browser on mac, and here it works perfectly.
WKWebView runs all of its networking in a separate process and thus does not ‘see’ your process’s cookie store.
The problem is that the WKWebView does not write back the cookies immediately. I think it does this on its own schedule. For example when a WKWebView is closed or maybe periodically.
In iOS 11 we added WKHTTPCookieStore to give you full access to the web view’s cookie store.
Supported cookie sync with WKWebView on older platforms is tricky. There are two techniques that might work:
You can set a cookie in the headers of the request you pass to
[WKWebView loadRequest:].
You can get and set cookies from within the web view by running
JavaScript code (using -evaluateJavaScript:completionHandler:) that
accesses the JavaScript document.cookie value.
For more reference https://forums.developer.apple.com/thread/95301 additionally some workaround Getting all cookies from WKWebView

iOS safely pass content between apps

I'm curious if there is a way to safely pass content between apps on iOS. The ultimate goal is to implement oauth between two ios apps.
Since apps are not guaranteed to have unique url schemes, this option is out.
I have considered using keychain groups, but do not have experience with this. It looks like an app needs to specify exactly which apps can access the keychain items.
Are there any other options? Is there some sort of identifier (such as android bundle ID) that can be used to verify the apps during a request?
You can use URL schemes for this.
The basic process
You'll have a ServerApp and many ClientApps. The ServerApp listens to an URL-scheme like serverapp://. The client then can make a call to the server to ask it for authentication. The client has to implement an URL-scheme too. E.g. ClientAppOne implements the URL scheme clientapp1://. The server takes as parameter a backlink to the client app. E.g. the client calls the URL serverapp://auth?back=clientapp1%3A%2F%2Fserverapp-auth (here the backlink is clientapp1://serverapp-auth and has been urlencoded).
The server then checks the users identity, asks him for permission, password, etc. and then uses the backlink to provide the data. How the backlink works exactly is application specific, but you usually need at least 2 parts: an access token and a username. E.g. a backlink will then be clientapp1://serverapp-auth?success=1&token=fi83ia8wfzi3s8fi8s3f8si8sf&user=robert or maybe in case of error clientapp1://serverapp-auth?success=0&errno=421. The client then needs to verify the accesstoken through some public (or private) API, e.g. https://serverapp.example.com/userdetails?apikey=fai83jw93fj93389j&token=fi83ia8wfzi3s8fi8s3f8si8sf. The server will return some structured response.
Necessary components
an URL scheme on the server App
an URL scheme on each client App
an SDK that is to be included into each client app and that handels the details of authentication, and a standard UI component (e.g. facebook has a standard button that says "login with facebook", so the ServerApp needs some re-recognizable button that says something like "login with ServerApp")
a server that provides services that can be accessed through the access token.
a defined API that explains how the client has to communicate with the server
an SDK to be included into the client that handels such client-server-communication (should be part of the SDK mentioned in component 3.)
maybe a wiki that documents all of the steps above, so that you and other developers dont lose track
a way to invalidate access tokens, and a way for the client to detect if an access token has been invalidated. furthermore, if the user changes his password, all access tokens should be invalidated.
Random notes
in your client app you can check if the serverapp is installed by calling [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:#"serverapp://auth"]].
the URL schemes should be sufficently collission-free. These URLs are never seen by users, only by developers, so they don't have to be beautiful. You can e.g. append the iTunes-Connect-App-ID to your URL-scheme, like serverapp1234567://. This will greatly reduce the possibility that someday some other app will use the same URL scheme.

Rails 3 and iOS Architecture Review

My goal is to build a standalone RESTful Rails 3 service that communicates with a Rails 3 web application via ActiveResource JSON and an iPhone application via iOS 5 native JSON. I have each running so that a single table of data is being exposed in the service app and that can be called and rendered via both a Rails app and the iPhone app.
My question is around authentication and something that can be reusable for both the web application and the iPhone app or in the future an Android app.
From the research I have done on this site, it seems HTTP Basic would work for both, however I would be unable to properly logout a user on the web side like sessions or cookies could and I have the browser login form to deal with. If I use sessions, how would that translate to setting up authentication on the iOS side of things?
This project is a code learning exercise, so I am hoping for implementation or architectural guidance rather than simply implementing Devise or Authlogic, etc.
It sounds like you're conflating at least two problems.
The first issue is authentication: you need to determine if the user is who they say they are. For authentication, you can do basic auth. You could also use client certs, though that's probably not what you're looking for.
The second thing is session management: First, you can do basic auth on each page request and store the session state in the database, but you're right about not being able to log the user out, as the browser will cache the credentials.
You may want to consider a login page that requires basic auth and shoots back a cookie to do session management. All other pages don't require basic auth, but give a 401 unauthorized if the cookie isn're present. Or you could redirect. The iOS client code will have to know to call the login page first to get the cookie and then use it after that. Logging out is deleting the cookie.. hrmm, but the browser will still cache the basic auth credentials.
I'm thinking the only way you're going to get what you want is to have a form-based auth for your web users (to allow them to log out and log in as someone else), and a basic-auth based system for iOS users. As a result of both authentication mechanisms, return a cookie that has to be used for all other pages.

Resources