LibertyDSNP / dsnp-wallet-swift

0 stars 0 forks source link

iOS > SPIKE > ASWebAuthenticationSession #95

Closed crbnlng closed 1 year ago

crbnlng commented 1 year ago

@crbnlng commented on Thu Mar 23 2023

Overview: In effort to streamline the use case where a user is adding their stand alone wallet key to an existing MSA, we would like to investigate if the in-app webview can detect a valid Custodial Site cookie and log user in vs directing them out to web.

Apple API: ASWebAuthenticationSession https://developer.apple.com/documentation/authenticationservices/authenticating_a_user_through_a_web_service

Overview of Concept:

  1. User migrates to DSNP on MeWe. On successful migration a cookie is created.
  2. Once a user creates keys in the stand alone wallet app, we want to detect if user has a valid cookie. If so, log them in and show prompt to add key to MSA. If cookie is NOT detected, show website Login screen.

Note We may need to reach out to Peter since there is a cookie creation aspect to this. i.e. how / where cookie is created so we know to look for it, determine if MeWe would need to change something on their side or if it's just in our webviews.

Requirements:

  1. Read the documentation for ASWebAuthenticationSession
  2. Create POC (if needed) to determine if the above flow can work
  3. Document the implementation details and any potential issues or limitations.
ryansheh commented 1 year ago

import UIKit import WebKit

class ViewController: UIViewController {

let webView = WKWebView()
let btn = UIButton(type: .system)

override func viewDidLoad() {
    setBtn()
}

func setBtn() {
    btn.setTitle("Open", for: .normal)
    btn.addTarget(self, action: #selector(tappedBtn(selector:)), for: .touchUpInside)
    btn.titleLabel?.textColor = .black
    btn.contentHorizontalAlignment = .center

    self.view.addSubview(btn)
    btn.translatesAutoresizingMaskIntoConstraints = false
    btn.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    btn.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    btn.widthAnchor.constraint(equalToConstant: 100).isActive = true
    btn.heightAnchor.constraint(equalToConstant: 100).isActive = true
}

func setWebView() {
    self.view.addSubview(webView)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    webView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
    webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}

func setCookie() {
    if let url = URL(string: "https://example.com") {
        // Create a cookie
        let cookieProperties: [HTTPCookiePropertyKey: Any] = [
            .name: "cookieName",
            .value: "cookieValue",
            .domain: "example.com",
            .path: "/",
            .expires: NSDate(timeIntervalSinceNow: 60 * 60 * 24 * 7) // expires in 1 week]
        ]
        if let cookie = HTTPCookie(properties: cookieProperties) {
            // Add the cookie to the shared cookie storage
            HTTPCookieStorage.shared.setCookie(cookie)
        }

        // Load the URL in a UIWebView
        let request = URLRequest(url: url)
        webView.load(request)
        getCookie()
    }
}

func getCookie() {
    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            if cookie.name == "cookieName" && cookie.value == "cookieValue" {
                // The cookie exists, do something
                print("Found the cookie!")
                return
            }
        }
    }

    print("No cookie :(")

}

@objc func tappedBtn(selector: UIButton?) {
    setWebView()
    setCookie()
}

}

ryansheh commented 1 year ago

Cookie setting and getting through WKWebView is possible in iOS. The code snippet above is a basic example illustrating such. The following properties that can be set with the cookie are as follows.

ryansheh commented 1 year ago

Cookies in iOS can be the same types of cookies used in Safari. This is because both Safari and iOS use the same cookie storage mechanism, the HTTPCookieStorage class, which is part of the Foundation framework.

When a user visits a website using Safari on their iOS device, any cookies that are set by that website will be stored in the same HTTPCookieStorage instance that is used by the iOS app. This means that if your iOS app accesses the HTTPCookieStorage instance, it can retrieve the same cookies that were set by Safari.

However, there are some limitations to cookie usage on iOS that may not be present in Safari. For example, iOS limits the amount of data that can be stored in cookies to 4KB per cookie, and the total amount of cookie storage space is limited to 600 cookies per domain. Additionally, the HTTPCookieStorage instance used by iOS apps is not shared between different apps, so cookies set by one app cannot be accessed by another app.

ryansheh commented 1 year ago

iOS — Each app and app extension has a unique data container, meaning they have separate cookie stores. You can obtain a common cookie storage by using the sharedCookieStorage(forGroupContainerIdentifier:) method.

Example

ryansheh commented 1 year ago

An iOS app can read a cookie dropped from Safari if the cookie is associated with a domain that the app has permission to access. By default, an app cannot access cookies that are dropped by Safari or other apps, as this would be a potential security risk. However, an app can be configured to request permission to access cookies from a specific domain by setting the NSHTTPCookieStorageAcceptPolicy property to NSHTTPCookieAcceptPolicyAlways or NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain.

Once the app has permission to access cookies from a specific domain, it can read any cookies that have been dropped by Safari or other apps for that domain. However, keep in mind that the app will only be able to access cookies that are associated with the domain and path that it has permission to access, and that the cookie may contain sensitive user data. It's important to handle cookies securely and to protect user privacy by using appropriate security measures, such as encryption and authentication.