Facebook - hippogamesunity/SimpleSignIn GitHub Wiki
Welcome to Simple Facebook Sign-In wiki!
The asset provides Facebook sign-in with OAuth 2.0 for Android, iOS, Windows, Mac, Universal Windows Platform (UWP) and WebGL apps made with Unity. You can also get access tokens to make REST API calls to other Facebook services.
Warning
Starting May 5, 2023, all apps making new requests for Advanced Access, including for email and public profile, will require Business Verification (stackoverflow).
Benefits
- Cross-platform user auth for cross-platform games and apps
- No plugins, no 3rd party libs, no dependencies
- No impact to build size
- Get access tokens to make Facebook API calls
- More security for client-server apps (get an access token on a client, get all user data on a server to avoid tampering)
- JSON Web Tokens (JWT) validation
Alternatives
- Facebook SDK for Unity (massive, Standalone and WebGL not supported)
Terminology
- Please visit Terminology section
Understanding how it works
-
Generic workflow (for platforms that support deep linking):
- Your app navigates users to Google
Authorization Endpointusing a default web browser (embedded webviews are not allowed) - Users perform sign-in using their login and password
- Google
Authorization Endpointredirects users toRedirect URI(this can be a deep link when possible) and provides an authorizationcodeto the app (as URI parameters) - The app is activated and obtains
code - The app exchanges
codeforaccess token - The app requests user data with
access token(ID, name, email and other data according access scope defined)
- Your app navigates users to Google
-
For Android, iOS, macOS, Windows and Universal Windows Platform (platforms that support deep linking):
Redirect URIis a deep link which activates the app and providescodein URI parameters
-
Loopback flow for Editor:
- This flow is optional for Windows (the generic workflow is used by default)
Redirect URIishttp://localhost:PORT/with a random unused port- The app listens to localhost using
System.Net.HttpListener - The app obtains
codeand asks a user to close the browser tab and to return to the app - Further workflow is the same (exchanging
codeforaccess token, requesting user data)
-
Middleware flow for WebGL (the platform doesn't support deep linking and loopback):
OAuth RedirecttoAuthorization Middlewareis used to temporary savecode- The app obtains
codefromAuthorization Middlewarewith a POST request - Further workflow is the same (exchanging
codeforaccess token, requesting user data)
Authorization Middleware
Authorization Middleware is used to workaround 2 issues:
- Facebook doesn't allow deep links for
Valid OAuth Redirect URIs(deep linking works for Android, iOS, macOS, UWP and ~Windows). - Standalone platforms (Windows and Mac) and WebGL don't support deep linking (direct
OAuth Redirectis not possible in this case).Authorization MiddlewarehandlesOAuth Redirectand temporarily savescodethat can be further requested by the app using POST.
Authorization Middleware has the following URL https://hippogames.dev/api/oauth/ and contains 3 methods:
initshould be called before navigating to FacebookAuthorization EndpointwithstateandRedirect URIparametersredirectis called by FacebookAuthorization Endpointwithstateandcodeafter users perform sign-ingetcodeshould be called from Standalone platforms (Windows and Mac) and WebGL to obtaincode
Can I trust Authorization Middleware? Is it secure to use a 3rd party service?
Authorization Middlewarecan't exchangecodeforaccess tokenwithout knowingcode verifier. It's generated by your app and kept in secret. Only the app itself can exchangecodeforaccess token.- It's recommended to deploy your own trusted
Authorization Middlewareto handle sensitive data. Please refer to Authorization Middleware article.
Preconditions
- Pick your
Custom URI scheme(orProtocol). In my example it issimple.auth, but it can bejelly.bean(note thatCustom URI schemeis not the same as your actual package name or bundle id). - For Android, iOS, UWP: enable deep linking as described in Unity documentation or as described below.
- For Android: create
AndroidManifest.xmlinsideAssets/Plugins/Android/, SET yourCustom URI schemeinside, like<data android:scheme="simple.auth" />. You can useAndroidManifestExample.xmlfrom the asset as an example, just copy, rename and edit. AGAIN, DON'T FORGET TO REPLACEsimple.authwith yourCustom URI scheme! - For iOS and macOS: navigate to
Player Settings > Other > Configurationand add yourCustom URI schemetoSupported URL schemes. In Xcode, make sure that the URL scheme is added (Register your URL scheme). - For Universal Windows Platform: navigate to
Player Settings > Publishing Settingsand setProtocol(it MUST contain a period symbol, for examplesimple.auth), then enableInternetClientinCapabilities. - For Windows: navigate to
Player Settingsand enableResolution and Presentation > Force Single Instanceand setOther Settings > Api Compatibility Level = .NET Framework
Setup steps
- Visit Meta for Developers
- Create a new app if needed (type:
Authenticate and request data from users with Facebook Login) - Make sure that
Facebook Loginis addedUse cases > Customize - Navigate to
Facebook Login > Settings > Valid OAuth Redirect URIsand addhttps://hippogames.dev/api/oauth/redirect - Copy
App ID - Set
App Mode: Liveand prepare your app for review (optional) - Return to Unity and configure
Resources/FacebookAuthSettings.asset- For Android, iOS, macOS, Windows and UWP: set
Client ID(which isApp ID) andCustom URI scheme(orProtocol) - For WebGL: set
Client ID(which isApp ID) only
- For Android, iOS, macOS, Windows and UWP: set
Usage
- Check our
Examplescene and C# code ofExample.cs - Create a new instance of
FacebookAuth - Call
FacebookAuth.SignInorFacebookAuth.GetAccessToken(for further API calls) - Create
OnSignInorOnGetAccessTokencallbacks - Build and test
- Write a review on the Asset Store :)
Best practices
- Call
FacebookAuth.SignInwithcaching: trueto return cachedUserInfo - Call
FacebookAuth.SignInwithcaching: falseto requestUserInfofrom Facebook - Call
FacebookAuth.GetAccessTokeninstead ofFacebookAuth.SignInif you need an access token only (and don't needUserInfo) - You can use
FacebookAuth.SavedAuthto getTokenResponseorUserInfo(don't forget to check all values for null) - Call
FacebookAuth.SignOutwhen 'Sign out` button is pressed (optional) - Disable debug logs for production by setting
FacebookAuth.DebugLog = false
Next steps (optional)
- You can add extra access scopes in
Resources/FacebookAuthSettings.asset - If you have a backend (server), send
TokenResponseto it (to avoid tapmering user data when sending from clients to your server) - Validate
JSON Web Token (JWT)encoded inTokenResponse.IdTokenon your server (refer toJWTclass for parsing and signature validation example) - For Editor, you can modify
StandaloneTemplate.html(used by the loopback flow) to edit the message "Success! Please close the browser tab and return to the app." - Consider deploying your own
Authorization Middleware
Notes
- Please refer to User data disclosure
- Don't use the default
App IDandCustom URI schemethat come with the asset in production, they are for test purposes only and can be disabled/blocked - Don't forget to send your Facebook app for review to remove limitations
- Don't forget to leave a review on the Asset Store
Known issues
- Please visit Common issues section
- Facebook Limited Login is not supported (different endpoints)
- All apps making requests for Advanced Access, including for email and public profile, require Business Verification
- When Facebook requests a one-time code (sent by email), it does not redirect the user to
Redirect URI, instead it shows the main user page (unfortunately, there is no way to fix this behaviour, and the only workaround is running the oauth flow again)