Vlad Dogadaev
Vlad Dogadaev

Reputation: 97

private API using Firebase Authentication

I'm creating private API for my app and trying to protect it with Google Auth. How can I get some new token every request so then I could verify it on my own server with some secret key?

In the Firebase dashboard I see web client secret, but there is neither any documentation on how to use it nor what this secret is.

Or maybe you know some good practices on how to create private API for only one application usage. Thanks!

Upvotes: 0

Views: 531

Answers (1)

Sanchita Santra
Sanchita Santra

Reputation: 359

It's a pretty long process :

Follow https://developers.google.com/identity/sign-in/android/ for the basic sign-in with Google Auth.

For using the authorization in the backend, there are some modifications -

Step 1 - Since you already found the client secrets file, use the client secret id to get the serverAuthCode. Like -

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestServerAuthCode(clientSecrets.getDetails().getClientId(), true)
                .requestEmail()
                .build();

Step 2 - In handleSignInResult method shown in the link, you can get your authCode which you will be sending to your server.

account.getServerAuthCode();

Step 3 - In your server, you can get the access token. This accessToken in used for using almost all Google APIs. Basically, getting accessToken means your backend is authenticated with Google.

Add the client secrets file to your backend.

GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(
                        JacksonFactory.getDefaultInstance(), new InputStreamReader(getAssets().open(Constants.CLIENT_SECRET_FILE_PATH)));


 if(!authCode.isEmpty()) {
            GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                    new NetHttpTransport(),
                    JacksonFactory.getDefaultInstance(),
                    "https://www.googleapis.com/oauth2/v4/token",
                    clientSecrets.getDetails().getClientId(),
                    clientSecrets.getDetails().getClientSecret(),
                    authCode,
                    "")
                    .execute();

            accessToken = tokenResponse.getAccessToken();
    }

There are a few more steps since the authCode can be used only once and the accessToken expires after a while and you have to request a new one with refreshToken. But, that isn't within the scope of this question.

Upvotes: 3

Related Questions