React Native: Authentication with WebView
This article was adapted from Jason Safaiyeh's article on Dev.to, found here: https://dev.to/safaiyeh/react-native-authentication-with-webview-1nh
You have a web application with all your features built out and now it is time to build your mobile app. You find yourself writing out the same business logic over again and think, "hmm maybe there is a quicker way to initially implement features, to iterate faster?"
Good news, you can! 🎉
Using the power of web views, mobile applications can wrap login flows and authenticate users without having to rewrite the logic.
Continue scrolling
↓React Native WebView
Let's get started with a powerful tool called react-native-webview
.
Starting with a basic example that loads the login page. Now the user can see the login page and go down any of the app's auth flows.
Features supported: Login, Sign Up, Forgot Password
URL Param Tokens
Some authentication flows will redirect to a URL containing the user's access token as a URL param.
Taking advantage of react-native-webview
's prop onNavigationStateChange
, we can watch the URL changes and act accordingly.
We will detect when the token is in the URL, then parse it out so it can be used in the mobile app. Now the user is authenticated and the token can be used in your app!
Features supported: URL Param Token-based Auth
Cookies Based Auth
For more complex auth flows, you may need several cookies to authenticate a user.
Taking advantage of react-native-webview
's prop onMessage
, we can send the document's cookies to the native code.
Every time navigationStateChange
is triggered, we will inject a script using injectJavaScript
this will return cookie information for onMessage
to process. Now the application has cookies for future requests.
Features Supported: Cookie Based Auth
Cookies Based Auth: iOS Quirk
WKWebView
stores session cookies on the device. It will not be returned in the CHECK_COOKIE
script we used above.
To get around this we need to use @react-native-community/react-native-cookies
to extract the cookies from the device cookie manager.
We need to set the sharedCookiesEnabled
prop to true. This tells WebView to save the cookies onto the native cookie manager.
Features Supported: iOS Support
Conclusion
Web views can be used in very creative ways to build mobile applications; especially, if you want to iterate quick.
Let me know if there are other ways of authenticating through web views or a different type of authentication that you want to be seen done!
Leave a comment if this was helpful or have any questions!
You can find me on Twitter @safaiyeh or maintaining react-native-webview
and @react-native-community/react-native-cookies
.
Keep Building!