ASWebAuthenticationSession get Cookies

759 Views Asked by At

im trying to use ASWebAuthenticationSession to authenticate with a private identity provider.

  1. Authentication with ASWebAuthenticationSession starts
  2. Callback with my custom scheme got called
  3. I need all Cookies of this requests to authenticate the User within my WKWebView. The callback only sends me the url of my custom scheme and not the request.

I can't transfer the Cookies within the url of my custom scheme because i reach the maximum length of url.

ASWebAuthenticationSession doesn't use HTTPCookieStorage to store the Cookies while the authentication?!

session = ASWebAuthenticationSession(url: urlToCall, callbackURLScheme: scheme)
    { callbackURL, error in
        let cookie = callbackURL?.absoluteString.split(separator: "=")[1]
        print("Session is \(cookie)")
        //How to get Cookies here?
    }

Does anyone have solutions?

1

There are 1 best solutions below

0
On

I run into the same problem, and unfortunately there is no way to get your cookies using ASWebAuthenticationSession

My solution was to use WKWebView for authentication rather than ASWebAuthenticationSession.

This will give you flexibility to achieve what you need mainly because you'll be able to access cookies from you WebView.

The main difference is that you will need to dismiss the WebView manually, and for this I would say we have to options:

  1. Once you pass the origin or callback url to your auth provider you will receive it in you scene delegate, and from there reach the code where you are presenting your WebView and dismiss it.
func scene(
    _ scene: UIScene, 
    openURLContexts URLContexts: Set<UIOpenURLContext>
) {
    print("SCENE-DELEGATE : Callback received")
    print(URLContexts)
}
  1. Implement WKNavigationDelegate, and check the redirect URL until it matches the final redirect in your auth process and dismiss the web view from there, this can be done in:
func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        if navigationAction.request.url?.host == "ssoResult" {
            UIApplication.shared.open(navigationAction.request.url!)
            <dismissYourWebView>
            decisionHandler(.cancel)
            return
        }
        decisionHandler(.allow)
    }

Finally to access the cookies WKWebView has it's own cookie storage so you probably don't need to do anything else and should be able to open a new WKWebView and this last one should have the cookies already.

Note: To read cookies in your WKWebView you can do do through:

WKWebsiteDataStore.default().httpCookieStore.getAllCookies { cookies in
          
      }