I am trying to implement OAuth using iOS URL schemes. For example if I provide myapp://
as redirect_uri
the app should launch. However, I cannot add it as OAuth domain in the Stack Apps settings, as it's not a domain. Is there a way to do that other than using the client side OAuth in a web browser with https://stackoverflow.com/oauth/login_success
as redirect_uri
then catching the access_token
from the link?
1 Answer
It is indeed possible to use custom URL schemes for authentication in an iOS app. Here are the steps I took:
Choose an arbitrary domain, like
stackexchange.com
, for the OAuth domain in your Stack Apps(Optional) Make sure it has a Stack Apps Post if you want tokens with write access.
Check the checkboxes for these options:
- Enable Client Side OAuth Flow
- Disable Desktop Application OAuth Redirect Uri
Register the custom URL scheme for your application in the usual way, as described e.g. here.
Use code like this to start the authentication flow (in Safari, not in the app itself). Substitute
54321
with the client ID from your Stack Apps listing. You may adjust thescope
according to the documentation, and of course theredirect_uri
, as long as the domain matches the one in the Stack Apps listing.let url = "https://stackoverflow.com/oauth/dialog?client_id=54321&scope=read_inbox,no_expiry,write_access,private_info&redirect_uri=example://stackexchange.com"; UIApplication.shared.open(URL(string: url)!) { (result) in }
Log in to Stack Overflow; your app will be opened and the URL will be something like
example://stackexchange.com/#access_token=12345))
where12345))
is the actual token.
An alternative is to use Universal Links to register a HTTP(S) URL you own, say https://furdui.example.com
with your iOS app. Then, you can use the domain furdui.example.com
as OAuth domain in Stack Apps, and have the redirects automatically forwarded to your iOS app.