r/iOSProgramming • • 6d ago

Question Is HTTP loopback OAuth actually feasible in a native iOS app? (Sign in with ChatGPT / SwiftUI)

I’m developing a native SwiftUI iOS app and trying to implement OpenAI’s Sign in with ChatGPT (SIWC) open-source plan-usage flow.
The documented flow requires:

  • A local HTTP callback at http://127.0.0.1:<port>/auth/callback
  • A local listener running before authorization starts
  • Opening the system browser
  • Receiving the authorization code through the loopback callback

My implementation uses Apple’s Network framework (NWListener) and opens the authorization page in external Safari.
On a physical iPhone, the OpenAI consent page loads and displays the correct account and subscription information. However, the consent button keeps spinning indefinitely, and the app never receives the callback.
My suspicion is that iOS suspends the app while external Safari is active, which prevents the local listener from receiving the redirect.
I’ve considered a few alternatives:

  1. SFSafariViewController to keep the app in the foreground.
  2. ASWebAuthenticationSession, although its callback handling does not appear to support HTTP loopback.
  3. An officially supported alternative OAuth flow for native iOS apps.

The problem is that OpenAI’s documented SIWC open-source flow explicitly requires HTTP loopback and a system browser.
My questions:

  • Has anyone successfully implemented a local HTTP loopback listener in a native iOS app while completing OAuth in an external browser?
  • Does iOS actually suspend NWListener when the app enters the background?
  • Could SFSafariViewController keep the listener alive, and would this be a technically sound approach?
  • Is there another standards-compliant approach that would work without changing the provider’s required redirect URI?

I’m specifically looking for a solution that does not involve API keys, cookie extraction, password handling, proxies, or undocumented endpoints.
Any practical experience or technical insight would be greatly appreciated.

3 Upvotes

14 comments sorted by

1

u/youthdancing 6d ago

I am interested in this as well. Did you try this yet? It should keep your app running in the background: https://developer.apple.com/documentation/backgroundtasks/performing-long-running-tasks-on-ios-and-ipados

1

u/Nian99 6d ago

Thanks for the suggestion! I hadn’t looked into BGContinuedProcessingTask yet.

I’m building this as a native SwiftUI app and using NWListener for the local HTTP callback. The tricky part is that the OAuth flow requires opening the system browser, which sends the app into the background while the user signs in and approves access.

Do you know if BGContinuedProcessingTask can actually keep an incoming NWListener connection alive during that time? I understand it can keep certain work running in the background, but I’m not sure whether that also covers a local TCP listener waiting for an incoming callback.

Have you tried anything similar yourself? Would be really interesting to hear how it behaves on an actual device.

1

u/youthdancing 6d ago

I am looking to implement a similar auth flow but I didn't get around testing it. For another purpose I use BGContinuedProcessingTask for a user-started operation: a series of local-network requests with polling in between, which can take a minute or more. The task keeps the app running, so normal requests and Task.sleep polling just work.

2

u/Green_Start2329 6d ago

Use https://developer.apple.com/documentation/authenticationservices (ASWebAuthenticationSession), that way the entire web authorization flow stays within your app, keeping the loopback listener alive.

"SFSafariViewController" won't work because it doesn't support things like Passkey authentication.

1

u/Doctor_Fegg 6d ago

ASWebAuthenticationSession plus a local webserver (using whatever the modern equivalent of GCDWebServer is) should work, shouldn’t it?

1

u/PiXeL161616 6d ago

Apple DTS covers the listener part here: a TCP connection can succeed while the app is suspended, but the app can't handle it, so the client hangs. Backgrounded isn't necessarily suspended. That makes suspension worth testing, but it doesn't establish why this consent page spins or whether BGContinuedProcessingTask fixes it.

1

u/laplace_apps 6d ago

Your suspicion is right. Once Safari is in front your app gets suspended, and the NWListener stops answering. beginBackgroundTask can buy a little time, but it's fragile and not something to ship on. ASWebAuthenticationSession is the proper in-app auth sheet. It keeps your app active, but it only completes on a custom scheme or (newer iOS) an https callback, not a loopback URL. So realistically: check whether the provider offers a device-code flow or lets you register a custom-scheme / universal-link redirect for mobile. If loopback is the only option, a small backend relay that receives the redirect and bounces to your universal link is the usual workaround, if their terms allow it.

1

u/DimensionMindless336 5d ago

The thing that made this click for me: the RFC 8252 loopback pattern is a desktop pattern. It assumes the browser and your app share one network namespace and that your app keeps running while the browser does its thing. On iOS neither holds -- once you jump to Safari your app gets suspended, and even when the TCP SYN reaches your NWListener (Apple DTS confirms this can happen while suspended) there is no live process to accept it and hand the code back. So the spinning consent button is less a bug in your listener than the pattern itself being the wrong tool on this platform.

One snag with the suggestion above: ASWebAuthenticationSession won't rescue a loopback redirect as-is. Its callbackURLScheme explicitly rejects http and https -- pass "http" and it ignores the callback, never fires completion, never dismisses the sheet. So "ASWebAuthSession + local webserver" doesn't actually work against a 127.0.0.1 redirect URI.

What does work is registering a real redirect with the provider and letting the OS do the return. Two shapes:

  1. A custom scheme like yourapp://oauth/callback. Set it as your OAuth redirect_uri, pass that scheme to ASWebAuthenticationSession, give it a presentationContextProvider, set prefersEphemeralWebBrowserSession = true (you want a clean ChatGPT login, not Safari's existing cookies), and use PKCE. ASWebAuthSession guarantees only your session receives that scheme's callback even if another app claims the same scheme -- that's the part you don't get by handling the scheme yourself in openURL.
  2. On iOS 17.4+ the newer init(url:callback:completionHandler:) with ASWebAuthenticationSession.Callback lets you match an https universal link tied to your associated domain. Cleaner than a custom scheme if you already own a domain.

Either way the code arrives in your completion handler through the system, no socket involved, so suspension stops mattering entirely.

If OpenAI's SIWC config genuinely only allows loopback and won't take a custom redirect_uri, then the honest options are the device-code flow (works well on iOS, no browser bounce at all) or a tiny backend with a public https redirect that deep-links back into the app. I went the custom-scheme route on my own app -- happy to paste the exact Info.plist and session setup if that helps.

1

u/zhiqingl 5d ago

Your suspicion is right: once Safari is in front your app gets suspended within a few seconds, and a suspended app can't accept on NWListener, so the redirect to 127.0.0.1 just hangs. Two things that work in practice: present the auth page in SFSafariViewController so your app stays foreground and the listener stays alive, or keep external Safari but wrap the flow in beginBackgroundTask (you only get ~30s, so it's fragile). ASWebAuthenticationSession is the "right" API but it wants a custom scheme or an https callback with associated domains, so it won't match a loopback-only redirect. If OpenAI offers a mobile/custom-scheme client type, that's the long-term fix.

1

u/ogunel 4d ago

Your suspicion is right. Once external Safari is in front, your app is suspended within seconds, and a suspended app's listening socket doesn't accept connections, so the redirect to 127.0.0.1 has nobody to talk to. A background task won't fix it reliably either.

The loopback part itself works fine on iOS while your app is running. We serve video to AVPlayer from a local server on 127.0.0.1 inside our app, with no Local Network permission prompt, since loopback isn't treated as local network. The fix is keeping your process in the foreground for the whole flow:

  • SFSafariViewController is presented inside your app, so your process stays active and the NWListener keeps running. The browser's request to 127.0.0.1 is device-local, so it reaches your listener. Read the code there, then dismiss.
  • ASWebAuthenticationSession should work the same way. It also keeps your app in the foreground, and it shares the user's Safari session, which is nicer for an existing login. It can't match an http callback, but you don't need it to: your listener gets the code, then you cancel the session yourself. Pass any scheme you never redirect to as callbackURLScheme.

Two details: bind the listener to 127.0.0.1 only, not all interfaces, and check the state parameter you get back, since any app on the device can reach that port while it's open. And stop the listener as soon as the code arrives.

1

u/LavaCreeperBOSSB Beginner 2d ago

If I remember correctly I've done something like this before but not with an external WebView. I've done it with one that's embedded inside the app

0

u/[deleted] 6d ago

[removed] — view removed comment

1

u/AutoModerator 6d ago

Hey /u/XenoCI_Hyunsoo, your content has been removed because Reddit has marked your account as having a low Contributor Quality Score. This may result from, but is not limited to, activities such as spamming the same links across multiple subreddits, submitting posts or comments that receive a high number of downvotes, a lack of recent account activity, or having an unverified account.

Please be assured that this action is not a reflection of your participation in our subreddit. This is simply an automated filter in place to reduce spam.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.