
Authorization through Google in Android and checking the token on the server
Recently, I wanted to create a personal project on android, and the main question was: how to uniquely identify the user forcing him to do as little as possible gestures? Of course this is a Google account. I tried to try many examples on the network - however, the API was updated several times during its existence, many methods did not work, my questions on Google+ about this were either not accepted at all by the environment, or were like “I never did this”.
In this article, I will try as simple as possible for beginners (like me) to describe my method of authorizing Google on android, receiving a token and checking this token on the server.
To start, you must have Google Play Services installed in the SDK. After installing them, you can import all the necessary libraries. The article is written with the expectation of Android Studio - he himself tells what needs to be imported.
You must have created an activity with a button.
To make it more familiar to the user, you can create a standard Google+ Sing-In button.
It will look like this:

Just add to your Layout:
We write in our activity:
Actually, we will assign an action to the button - call the account selection intend. If you work in Android Studio, he will tell you which libraries you need to import, so I won’t describe this in detail here.
startActivityForResult (intent, 123); - sets the code with which the return will occur. 123 is a return code; it can be anything. This is necessary when you are doing several intends, and you need to process them differently.
Declare these variables in the class. These are the access areas we need. The first is written in google: “Allows you to define an authenticated user. To do this, when calling the API, you must specify me instead of the Google+ user ID. »The second permission we need to receive personal user data (Name, Surname, G + page address, avatar), and the latter to receive E-mail. I found this important, because this is a completely unchanged identifier for writing to the database.
Initially forgot this item - corrected.
We need to go to code.google.com/apis/console to create a project there, go to Credentials and create a new Client ID for OAuth by choosing Installed Application -> Android. There we need to enter the name of our package and the SHA1 amount of our key.
With this, I actually had a lot of problems solved in a rather crutal way.
Found debug.keystore in% USERPROFILE% \. Android \ debug.keystore placed in the project folder and registered in build.grandle:
After which we need to run the command:
keytool -exportcert -alias androiddebugkey -keystore ~ / .android / debug.keystore -v -list Keytool
itself can be found in the SDK. From the output, copy SHA1 to the desired field.
As I understand it, the method is temporary, and for normal operation you need to create a normal key. But for testing this is enough.
Where 123 is your code that you indicated earlier, where AcrivityName is the name of your activity. Roughly speaking - we feed the necessary token permissions and account name to the token receiving function. And note - this all happens in the background, after which the received token is transferred to the reg function I wrote. It already sends the token and all the necessary data to the server.
Since I’ve been developing recently, with exceptions, it’s a trouble so far, if there is a proposal, write in a personal message or in a comment.
I want to pay attention, the token we received is of type Online. And he acts only 10 minutes. To get an offline token (in order to work longer with it from the server), refer to this instruction developers.google.com/accounts/docs/CrossClientAuth
Actually feed the token in googleapis and pick up the received JSON response.
Perhaps the code is raw and written quite crookedly. However, I killed a whole week to find a working solution. I found this solution here: android-developers.blogspot.ru/2012/09/google-play-services-and-oauth-identity.html , although it was not fully functional, much has been added to this article.
I’m ready to hear suggestions for improving the article in PM or in the comments. Hope to save some time for beginners.
In this article, I will try as simple as possible for beginners (like me) to describe my method of authorizing Google on android, receiving a token and checking this token on the server.
Little preparation
To start, you must have Google Play Services installed in the SDK. After installing them, you can import all the necessary libraries. The article is written with the expectation of Android Studio - he himself tells what needs to be imported.
You must have created an activity with a button.
To make it more familiar to the user, you can create a standard Google+ Sing-In button.
It will look like this:

Just add to your Layout:
Add action to the button
We write in our activity:
View btn = (View) findViewById(R.id.sign_in_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, 123);
}
});
Actually, we will assign an action to the button - call the account selection intend. If you work in Android Studio, he will tell you which libraries you need to import, so I won’t describe this in detail here.
startActivityForResult (intent, 123); - sets the code with which the return will occur. 123 is a return code; it can be anything. This is necessary when you are doing several intends, and you need to process them differently.
Required Access Areas
Declare these variables in the class. These are the access areas we need. The first is written in google: “Allows you to define an authenticated user. To do this, when calling the API, you must specify me instead of the Google+ user ID. »The second permission we need to receive personal user data (Name, Surname, G + page address, avatar), and the latter to receive E-mail. I found this important, because this is a completely unchanged identifier for writing to the database.
private final static String G_PLUS_SCOPE =
"oauth2:https://www.googleapis.com/auth/plus.me";
private final static String USERINFO_SCOPE =
"https://www.googleapis.com/auth/userinfo.profile";
private final static String EMAIL_SCOPE =
"https://www.googleapis.com/auth/userinfo.email";
private final static String SCOPES = G_PLUS_SCOPE + " " + USERINFO_SCOPE + " " + EMAIL_SCOPE;
Register our application.
Initially forgot this item - corrected.
We need to go to code.google.com/apis/console to create a project there, go to Credentials and create a new Client ID for OAuth by choosing Installed Application -> Android. There we need to enter the name of our package and the SHA1 amount of our key.
With this, I actually had a lot of problems solved in a rather crutal way.
Found debug.keystore in% USERPROFILE% \. Android \ debug.keystore placed in the project folder and registered in build.grandle:
signingConfigs {
debug {
storeFile file("debug.keystore")
}
myConfig {
storeFile file("debug.keystore")
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
}
}
After which we need to run the command:
keytool -exportcert -alias androiddebugkey -keystore ~ / .android / debug.keystore -v -list Keytool
itself can be found in the SDK. From the output, copy SHA1 to the desired field.
As I understand it, the method is temporary, and for normal operation you need to create a normal key. But for testing this is enough.
Token receipt code
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent data) {
if (requestCode == 123 && resultCode == RESULT_OK) {
final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
AsyncTask getToken = new AsyncTask() {
@Override
protected String doInBackground(Void... params) {
try {
String token = GoogleAuthUtil.getToken(AcrivityName.this, accountName,
SCOPES);
return token;
} catch (UserRecoverableAuthException userAuthEx) {
startActivityForResult(userAuthEx.getIntent(), 123);
} catch (IOException ioEx) {
Log.d(TAG, "IOException");
} catch (GoogleAuthException fatalAuthEx) {
Log.d(TAG, "Fatal Authorization Exception" + fatalAuthEx.getLocalizedMessage());
}
return token;
}
@Override
protected void onPostExecute(String token) {
reg(token);
}
};
getToken.execute(null, null, null);
}
}
Where 123 is your code that you indicated earlier, where AcrivityName is the name of your activity. Roughly speaking - we feed the necessary token permissions and account name to the token receiving function. And note - this all happens in the background, after which the received token is transferred to the reg function I wrote. It already sends the token and all the necessary data to the server.
Since I’ve been developing recently, with exceptions, it’s a trouble so far, if there is a proposal, write in a personal message or in a comment.
Check the token on the server. (Php)
I want to pay attention, the token we received is of type Online. And he acts only 10 minutes. To get an offline token (in order to work longer with it from the server), refer to this instruction developers.google.com/accounts/docs/CrossClientAuth
$mToken = $_POST['plusToken'];
$userinfo = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' . $mToken;
$json = file_get_contents($userinfo);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$tokenUserId = $userInfoArray['user_id'];
Actually feed the token in googleapis and pick up the received JSON response.
Conclusion
Perhaps the code is raw and written quite crookedly. However, I killed a whole week to find a working solution. I found this solution here: android-developers.blogspot.ru/2012/09/google-play-services-and-oauth-identity.html , although it was not fully functional, much has been added to this article.
I’m ready to hear suggestions for improving the article in PM or in the comments. Hope to save some time for beginners.