- Авторизация через Google в Android и проверка токена на сервере
- Небольшая подготовка
- Добавляем действие на кнопку
- Необходимые области доступа
- Регистрация нашего приложения.
- Код получения токена
- Проверяем токен на сервере. (PHP)
- Integrating Google Sign-In into Your Android App
- Before you begin
- Configure Google Sign-in and the GoogleSignInClient object
- Check for an existing signed-in user
- Add the Google Sign-in button to your app
- Start the sign-in flow
- Try Sign-In for Android
- Get the project
- Configure a Google API project
- Run the sample
- How it works
- Next steps
- Google Login Android using Firebase Tutorial
- Google Login Android using Firebase Video Tutorial
- Google Login Android using Firebase
- Creating an Android Project
- Enabling Google Login in Firebase Console
- Adding Dependencies
- Adding Google Sign-In Button to Activity
- Creating a Profile Activity
- Performing Google Sign-In
- Getting Some Basic Info from Google
- Adding Glide
- Displaying User Information
- Google Login Android Tutorial Source Code Download
- Checkout these tutorials as well:
- 12 thoughts on “Google Login Android using Firebase Tutorial”
Авторизация через Google в Android и проверка токена на сервере
Недавно мне захотелось создать личный проект на андроиде, и основной вопрос был такой: как однозначно идентифицировать пользователя заставляя его делать как можно меньше телодвижений? Конечно же это аккаунт Google. Я пытался пробовать множество примеров в сети — однако API несколько раз обновилось за время своего существования, многие методы не работали, мои вопросы в Google+ по этому поводу либо были вообще никак не восприняты окружением, либо были вроде «Никогда такое не делал».
В этой статье я постараюсь как можно более просто для новичков (вроде меня) описать мой метод авторизации в Google на андроид, получения токена и проверке этого самого токена на сервере.
Небольшая подготовка
Для начала — у вас должны быть установлены Google Play Services в SDK. После их установки можно будет импортировать все необходимые библиотеки. Статья пишется с расчетом на Android Studio — он сам подсказывает, что необходимо импортировать.
У вас должно быть создано активити с кнопкой.
Чтобы было привычнее пользователю можете создать стандартную кнопку Google+ Sing-In
Выглядеть она будет вот так:
Просто добавьте в ваш Layout:
Добавляем действие на кнопку
Пишем в нашем активити:
Собственно присвоим кнопке действие — вызов интенда выбора аккаунта. Если вы работаете в Android Studio он сам вам подскажет, какие библиотеки нужно импортировать, так что это подробно тут я расписывать не буду.
startActivityForResult(intent, 123); — задает код с которым произойдет возврат. 123 это код возврата, он может быть каким угодно. Это необходимо, когда вы делаете несколько интендов, и вам надо обработать их по разному.
Необходимые области доступа
Обьявите эти переменные в классе. Это необходимые нам области доступа. Первый написано в google: «Позволяет определить аутентифицированного пользователя. Для этого при вызове API необходимо указать me вместо идентификатора пользователя Google+. » Второе разрешение нам необходимо для получения личных данных пользователя (Имя, Фамилия, адрес G+ страницы, аватар), и последнее для получения E-mail. Я посчитал это важным, ведь это вполне неизменный идентификатор для записи в бд.
Регистрация нашего приложения.
Изначально забыл этот пункт — исправляюсь.
Нам необходимо зайти на code.google.com/apis/console создать там проект, зайти в Credentials и создать новый Client ID для OAuth выбрав пункт Installed Application -> Android. Там нам необходимо ввести название нашего пакета и SHA1 сумму нашего ключа.
С этим у меня на самом деле было много проблем решил достаточно костыльным способом.
Нашел debug.keystore в %USERPROFILE%\.android\debug.keystore поместил в папку с проектом и прописал в build.grandle:
После чего нам нужно выполнить команду:
keytool -exportcert -alias androiddebugkey -keystore
/.android/debug.keystore -v -list
Сам keytool можно найти в SDK. Из вывода копируем SHA1 в нужное поле.
Как я понимаю метод временный, и для нормальной работы надо создать нормальный ключ. Но для тестирования этого достаточно.
Код получения токена
Где 123 — ваш код, который вы указали ранее, где AcrivityName — название вашего актитивити. Грубо говоря — мы скармливаем функции получения токена необходимые разрешения и имя аккаунта. И заметьте — это все происходит в фоновом режиме, после чего полученный токен передается в написанную мною функцию reg. Она уже отправляет токен и все необходимые данные на сервер.
Так как разрабатываю недавно, с исключениями пока что беда, если есть предложение — напишите в личку или в комментарии.
Проверяем токен на сервере. (PHP)
Хочу обратить внимание, полученный нами токен имеет тип Online. И действует он лишь 10 минут. Для получения offline токена (чтобы дольше работать с ним с сервера) обратитесь к этой инструкции developers.google.com/accounts/docs/CrossClientAuth
Собственно скармливаем токен в googleapis и забираем полученный JSON ответ.
Источник
Integrating Google Sign-In into Your Android App
To integrate Google Sign-In into your Android app, configure Google Sign-In and add a button to your app’s layout that starts the sign-in flow.
Before you begin
Configure Google Sign-in and the GoogleSignInClient object
In your sign-in activity’s onCreate method, configure Google Sign-In to request the user data required by your app. For example, to configure Google Sign-In to request users’ ID and basic profile information, create a GoogleSignInOptions object with the DEFAULT_SIGN_IN parameter. To request users’ email addresses as well, create the GoogleSignInOptions object with the requestEmail option.
If you need to request additional scopes to access Google APIs, specify them with requestScopes . For the best user experience, on sign-in, only request the scopes that are required for your app to minimally function. Request any additional scopes only when you need them, so that your users see the consent screen in the context of an action they performed. See Requesting Additional Scopes.
Then, also in your sign-in activity’s onCreate method, create a GoogleSignInClient object with the options you specified.
Check for an existing signed-in user
In your activity’s onStart method, check if a user has already signed in to your app with Google.
If GoogleSignIn.getLastSignedInAccount returns a GoogleSignInAccount object (rather than null ), the user has already signed in to your app with Google. Update your UI accordingly—that is, hide the sign-in button, launch your main activity, or whatever is appropriate for your app.
If GoogleSignIn.getLastSignedInAccount returns null , the user has not yet signed in to your app with Google. Update your UI to display the Google Sign-in button.
Add the Google Sign-in button to your app
Optional: If you are using the default sign-in button graphic instead of providing your own sign-in button assets, you can customize the button’s size with the setSize method.
In the Android activity (for example, in the onCreate method), register your button’s OnClickListener to sign in the user when clicked:
Start the sign-in flow
Starting the intent prompts the user to select a Google account to sign in with. If you requested scopes beyond profile , email , and openid , the user is also prompted to grant access to the requested resources.
After the user signs in, you can get a GoogleSignInAccount object for the user in the activity’s onActivityResult method.
The GoogleSignInAccount object contains information about the signed-in user, such as the user’s name.
You can also get the user’s email address with getEmail , the user’s Google ID (for client-side use) with getId , and an ID token for the user with getIdToken . If you need to pass the currently signed-in user to a backend server, send the ID token to your backend server and validate the token on the server.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Try Sign-In for Android
Use our Android sample app to see how Sign-In works, or add Sign-In to your existing app.
Get the project
If this is your first time using a Google services sample, check out the google-services repository.
Open Android Studio.
Select File > Open, browse to where you cloned the google-services repository, and open google-services/android/signin .
Configure a Google API project
To use the sample, you need to provide some additional information to finish setting up your project. Click the button below, and specify the package name com .google .samples .quickstart .signin when prompted. You will also need to provide the SHA-1 hash of your signing certificate. See Authenticating Your Client for information.
The sample’s IdTokenActivity and ServerAuthCodeActivity examples require you to specify an OAuth 2.0 web client ID. In a real app, this client ID would represent your app’s backend server. A client ID for this purpose was created when you configured the project above.
Find this value by opening the Google API Console:
Your web server client ID is displayed next to Web client (Auto-created for Google Sign-in). Copy and paste the client ID into your project’s strings.xml file:
Run the sample
Now you’re ready to build the sample and run it from Android Studio.
Build the sample and click the run button and select a connected device or emulator with the latest version of Google Play services.
How it works
The application builds a GoogleSignInClient , specifying the sign-in options it needs. Then, when the sign-in button is clicked, the application starts the sign-in intent, which prompts the user to sign in with a Google account.
Next steps
If you want to see how you can implement Google Sign-In in your own app, take a look at our implementation guide.
Did you have a good experience? Run into trouble? Let us know!
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Google Login Android using Firebase Tutorial
Here is the Google Login Android Tutorial. If you are looking to integrating Google Login in your android application, then it is the right place.
Puting a Google Login in your Android Application is a perfect idea, as people hate filling forms, and remembering passwords. So if a Google Login is there on your android application, then it becomes convenient for your users to SignUp and SignIn in your app.
Here to integrate Google Login, I am going to use Firebase. Like the old way of adding Google Login in the app is obsolete and now google recommends using Firebase.
So let’s learn how to Integrate Google Login in Android.
Google Login Android using Firebase Video Tutorial
- You can watch this detailed video as well. Here I am covering the Google Login using Firebase step by step.
Google Login Android using Firebase
As always we will start a new Android Studio Project.
Creating an Android Project
- Open Android Studio (Here I am using Android Studio 3.0). And you need to create a project with an Empty Activity. I created a project named GoogleLoginExample.
- Once your project is loaded then click on Tools->firebase
- Then you will see a new window on the right. Here you need to select Authentication.
- Now you need to connect to firebase. It will again open a window, and from this window, you can create a new Firebase Project, or if you want you can also choose an existing one.
- After connecting to Firebase, click on Add Authentication and accept the changes. It will add all the required dependencies.
Enabling Google Login in Firebase Console
- If we want to use Google Login with Firebase, then we also need to enable it in the Firebase Console (Default disables it).
- To enable it, go to Firebase Console (console.firebase.google.com). Then from the right, select Authentication, then select SIGN-IN METHOD, and here you need to allow Google Option. (See the image below it is disabled, and you need to enable it).
Adding Dependencies
- We added the Firebase Dependencies in above step, but we need to add one more. To do this open your app level build.gradle file and add the line as shown below.
- Be sure you are using the same versions of firebase-auth, and play-services-auth.
Adding Google Sign-In Button to Activity
- Though you can use any button, we have an inbuilt Google Sign-In button. So here I will be using the default Google Sign-In button that is inbuilt.
- Come inside activity_main.xml and write the following code to add the Google Sign-In Button.
- You will see the following layout after writing the above code in your activity_main.xml.
Creating a Profile Activity
- On successful login, we will take the user to a Profile Screen. Create a new Empty Activity named ProfileActivity.
- On the layout file activity_profile.xml write the following xml code.
Performing Google Sign-In
- Here comes the most important thing. Come on MainActivity.java and write the following code.
- Now you can try running your application. You should be navigated to the Profile Activity (Check the Video).
Getting Some Basic Info from Google
- On successful login, you can get the user’s display name, profile picture, and email. For the profile image, you will get the URL to the image. So to display the image we again need a library called Glide, and it will help us in loading image from a URL.
Adding Glide
- Again add the following line inside you app level build.gradle.
- Now on the project level build.gradlle add the following.
- Now sync your project and you are done.
Displaying User Information
- Now, come inside ProfileActivity.java and write the following code.
- Now, you can try running the application.
Bingo! It is working fine.
Google Login Android Tutorial Source Code Download
- If you are having any troubles, then I have my source code for you as well. Unlock the below link to download source code.
So that’s it for this Google Login Android Tutorial friends. Let me know in the comment section if you have any confusions.
Also if you found this Google Login Android Tutorial helpful, then please SHARE it with your friends. Thank You 🙂
Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
Checkout these tutorials as well:
12 thoughts on “Google Login Android using Firebase Tutorial”
Post one more Demo Related to sync-adapter or Account Authentication
how to generate automated email or text message on mobile number. what i want is whenever there is a new user registration ,the username and password should be either mailed or texted to the number(without using any carrier service).
reply soon,
thanks,
newbie
if (mAuth.getCurrentUser() == null) <
finish();
startActivity(new Intent(this, MainActivity.class));
>
>
>
When the last authentication is completed, the moving code may need to be modified
As a ProfileActivity, not as the MainActivity
Thank you for your lecture.
can you help me with sign out of google.
i am using my sign out btn in navigation drawer it does not work.
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) <
drawerLayout.closeDrawer(GravityCompat.START);
if(menuItem.getItemId() == R.id.post) <
Toast.makeText(this, “This is post here”, Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, MyPostActivity.class);
startActivity(i);
>
if(menuItem.getItemId() == R.id.search) <
Toast.makeText(this, “This is post here”, Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, SearchActivity.class);
startActivity(i);
>
if(menuItem.getItemId() == R.id.logout) <
signOut();
>
return true;
>
//This is the signout method here
private void signOut() <
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener() <
@Override
public void onComplete(@NonNull Task task) <
Toast.makeText(MainActivity.this, “Signout Sucessfully”, Toast.LENGTH_SHORT).show();
finish();
>
>);
>
I integrate google login in my app at works a testing time but when i am upload app in play store it cant work so please help me
Sit this is working only test time but I will be generated singapk after this is not working please help me for this reply please…
Sit this is working only test time but I will be generated singapk after this is not working please help me for this reply please…
Источник