Google - hippogamesunity/SimpleSignIn GitHub Wiki
Welcome to Simple Google Sign-In wiki!
The asset provides Google sign-in with OAuth 2.0 for Android, iOS, Windows, macOS, Universal Windows Platform (UWP) and WebGL apps made with Unity. You can also get access tokens to make REST API calls to other Google services.
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 for integration with other Google services
- 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
- SFSafariViewController is used on iOS (required by App Store review)
- Deep linking for Windows (UNITY_STANDALONE_WIN)
Alternatives
Sign-in with Play Gamesfor Android (a part of Google Play Game Services, difficult to setup, super massive with a lot of dependencies, you can't get user email anymore in last versions)Sign-in with Applefor iOS (native, but there are issues with getting user emails)- 3rd party SDK for other platforms
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 and Windows (optional):
- 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)
Preconditions
- For Android, iOS, macOS, Windows and UWP (platforms that support deep linking): COME UP WITH your
Custom URI scheme(orProtocol). It MUST contain the period symbol.and small (LOWERCASE) alphanumeric symbols only (no spaces, no undercores). In my example it issimple.oauth, but it can bejelly.bean(note thatCustom URI schemedoesn't have to be 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.oauth" />. You can useAndroidManifestExample.xmlfrom the asset as an example, just copy, rename and edit. AGAIN, DON'T FORGET TO REPLACEsimple.oauthwith 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.oauth), then enableInternetClientinCapabilities. - For Windows: navigate to
Player Settingsand enableResolution and Presentation > Force Single Instanceand setOther Settings > Api Compatibility Level = .NET Framework - For Editor: Set
Allow downloads over HTTP = Always allowed(Unity 2022+)
Setup steps
- Visit Google Cloud > Credentials
- Create a new app if needed
- Create OAuth client ID
- For Android, iOS, macOS, Windows and UWP: select
iOS(for all 3 platforms, it's not a typo) and fillBundle IDwith your appCustom URI schemeorProtocol(see Preconditions). AGAIN, IT SHOULD BE EXACTLYiOS(this is the most common mistake)! Screenshot - For Editor and Windows (optional): select
Desktop appScreenshot - For WebGL select
Web applicationand provideAuthorized JavaScript origins(the URL of your published app) andAuthorized redirect URIs(SETAuthorization MiddlewareURL:https://hippogames.dev/api/oauth/redirect) Screenshot
- For Android, iOS, macOS, Windows and UWP: select
- Copy
Client ID(check if you didn't copy it with extra spaces)- For Windows, WebGL and Editor: copy
Client secretas well
- For Windows, WebGL and Editor: copy
- Configure
Resources/GoogleAuthSettings.asset- For Android, iOS, macOS, Windows and UWP: set
Client IDandCustom URI scheme(orProtocol) - For WebGL, Editor and Windows (optional): set
Client IDandClient secret - Check
Access Scopes(openid,email,profileare required to getUserInfo)
- For Android, iOS, macOS, Windows and UWP: set
Checklist
-
Custom URI schemeis picked, and it has a different value thansimple.oauth -
Custom URI schemeis set in 3 places: [1] Google Cloud credentials (Bundle ID), [2] Resources/GoogleAuthSettings.asset, [3] your application manifest (AndroidManifest.xml for Android,Supported URL schemesfor iOS,Protocolfor UWP) -
ClientIdis copied to Resources/GoogleAuthSettings.asset (check if you didn't paste it with extra spaces)
Usage
- Check our
Examplescene and C# code ofExample.cs - Create an instance of
GoogleAuth - Call
GoogleAuth.SignInorGoogleAuth.GetTokenResponse - Create
OnSignInorOnGetTokenResponsecallbacks - Build and test
- Write a review on the Asset Store :)
API reference for GoogleAuth class
| Method | Arguments | Description |
|---|---|---|
| GoogleAuth (constructor) | GoogleAuthSettings settings = null | A constructor that accepts an instance of GoogleAuthSettings. If Null is passed, it will load default settings from Resources (GoogleAuthSettings scriptable object). |
| SignIn | Action<bool, string, UserInfo> callback, bool caching = true | Performs sign-in and returns an instance of UserInfo with callback. If caching is True, it will return the previously saved UserInfo. |
| SignOut | bool revokeAccessToken = false | Performs sign-out. Can revoke Access Token if requested. |
| GetTokenResponse | Action<bool, string, TokenResponse> callback | Returns an instance of TokenResponse which contains AccessToken and other related information (expiration, type and other). It may also contain IdToken (JWT), if requested with openid scope, which contains information about the user. |
| GetAuthorizationCode | Action<bool, string, string> callback | Returns AuthorizationCode. It can be exchanged for AccessToken later (on your backend, for example). |
| TryResume | Refer to code | This can be called on app startup to continue OAuth. In some scenarios, the app may be terminated while the user performs sign-in on Google website. |
| SignInAsync | Async version of SignIn. | |
| GetTokenResponseAsync | Async version of GetTokenResponse. |
Best practices
- Call
GoogleAuth.SignInwithcaching: trueto return cachedUserInfo - Call
GoogleAuth.SignInwithcaching: falseto requestUserInfofrom Google - Call
GoogleAuth.GetTokenResponseinstead ofGoogleAuth.SignInif you need an access token or an ID token only (and don't needUserInfo) - You can use
GoogleAuth.SavedAuthto getTokenResponseorUserInfo(don't forget to check all values for null) - Call
GoogleAuth.SignOutwhen 'Sign out` button is pressed (optional) - Disable debug logs for production by setting
GoogleAuth.DebugLog = false
Next steps (optional)
- You can add extra access scopes in
Resources/GoogleAuthSettings.asset - If you have a backend (server), send
TokenResponseto it (to avoid tampering 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 and Windows (optional), 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." - For Windows, check Settings for Windows
- For WebGL, consider deploying your own
Authorization Middleware - You can use this asset with
asyncmethods, just refer toGoogleAuthAsync.csfor examples
Unity Authentication Service
Can I trust Authorization Middleware? Is it secure to use a 3rd party service?
Authorization Middlewarecan't exchangecodeforaccess tokenwithout knowing bothclient secretandcode verifier. 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.
Notes
- Please refer to User data disclosure
- Google OpenID is not the same as Play Games ID (Google Play Game Services), but they both have the same user email
- Don't use default credentials that come with the asset in production, they are for test purposes only and can be disabled/blocked
- You can use the same
iOScredentials for Android, iOS, Windows and UWP - Check Manual cancellation if needed
Known issues
- Please visit Common issues section
Supported browsers
- Please visit Supported browsers section
Try in real apps
Navigate: Menu/Google Drive Backup/Sign in with Google (for WebGL: Account/Sign in with Google).