Server side API Access - StansAssets/com.stansassets.android-native GitHub Wiki

When you configure Google Sign-In, build the AN_GoogleSignInOptions object with the RequestServerAuthCode method and specify the scopes that your app's backend needs to access with the RrequestScopes method.

Pass your server's client ID to the RequestServerAuthCode method.

using SA.Android.GMS.Auth;
using SA.Android.GMS.Drive;
...

AN_GoogleSignInOptions.Builder builder = new AN_GoogleSignInOptions.Builder(AN_GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
builder.RequestId();
builder.RequestEmail();
builder.RequestProfile();

string serverId = "YOUR_SERVER_CLIENT_ID_HERE";
// For example if you need Snapshot support add the APPFOLDER scope.
builder.RequestScope(AN_Drive.SCOPE_APPFOLDER);
builder.RequestServerAuthCode(serverId, false);
AN_GoogleSignInOptions gso =  builder.Build();

After the user successfully signs in, get an auth code for the user using AN_GoogleSignInAccount:

using SA.Android.GMS.Auth;
...

if (signInResult.IsSucceeded) {
    AN_GoogleSignInAccount account = signInResult.Account;
    string authCode = account.GetServerAuthCode();
    Debug.Log("authCode: " + authCode);
}

Then send the auth code to your app's backend using HTTPS POST.

On your app's backend server, exchange the auth code for access and refresh tokens. Use the access token to call Google APIs on behalf of the user and, optionally, store the refresh token to acquire a new access token when the access token expires.

If you requested profile access, you also get an ID token that contains basic profile information for the user.

Id Token

Make sure you request it when building the AN_GoogleSignInOptions object.

using SA.Android.GMS.Auth;
using SA.Android.GMS.Drive;
...

AN_GoogleSignInOptions.Builder builder = new AN_GoogleSignInOptions.Builder(AN_GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);

//other builder configurations
//The client ID of the server that will verify the integrity of the token.
string serverClientId = "YOUR_SERVER_CLIENT_ID_HERE";
builder.RequestIdToken(serverClientId);

AN_GoogleSignInOptions gso =  builder.Build();

After the user successfully signs in, get an auth code for the user using AN_GoogleSignInAccount:

using SA.Android.GMS.Auth;
...

if (signInResult.IsSucceeded) {
    AN_GoogleSignInAccount account = signInResult.Account;
    string token = account.GetIdToken();
    Debug.Log("token: " + token);
}

Google ID tokens are issued for one hour validity and will expire, you can simply use silentSignIn in your app to get a new one without any user interaction. If your existing token hasn't expired yet, you will get the (cached) version back. if it expired already, you will get a refreshed one, but it will take a little longer.