- Авторизация через Google в Android и проверка токена на сервере
- Небольшая подготовка
- Добавляем действие на кнопку
- Необходимые области доступа
- Регистрация нашего приложения.
- Код получения токена
- Проверяем токен на сервере. (PHP)
- Try Sign-In for Android
- Get the project
- Configure a Google API project
- Run the sample
- How it works
- Next steps
- Display the Sign In With Google button
- Prerequisites
- Button rendering
- JavaScript
- Credential handling
- Popup mode
- Redirect mode
- Your login endpoint URI
- Android sign in with google button
- Latest commit
- Git stats
- Files
- README.md
- About
Авторизация через 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 ответ.
Источник
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.
Источник
Display the Sign In With Google button
Add a Sign In With Google button to your site to enable users to sign-up or sign-in to your web app. Use either HTML or JavaScript to render the button and attributes to customize the button shape, size, text, and theme.
After a user selects a Google Account and provides their consent, Google shares the user profile using a JSON Web Token (JWT). For an overview of the steps involved during sign-in and user experience see How it works. Understand the personalized button reviews the different conditions and states affecting how the button is displayed to users.
Key Point: Our Code Generator helps you to interactively design your Sign In With Google button and generates the code needed to add it to your web page.
Prerequisites
Complete the following before adding the button to your login page:
- Follow the steps described in Setup to configure your OAuth Consent Screen and to obtain a Client ID.
- Load the client library.
Button rendering
To display the Sign In With Google button, you may choose either HTML or JavaScript to render the button on your login page:
Render the sign-in button using HTML, returning the JWT to your platform’s login endpoint.
An element with a g_id_signin class renders as a Sign In With Google button. The button is customized by the parameters provided in the data attributes.
To display a Sign In With Google button and Google One Tap on the same page, remove data-auto_prompt=»false» . This is recommended to reduce friction and improve sign-in rates.
JavaScript
Render the sign-in button using JavaScript, returning the JWT to the browser’s JavaScript callback handler.
The element specified as the first parameter to renderButton displays as a Sign In With Google button. In this example buttonDiv is used to render the button on the page. The button is customized using the attributes specified in the second parameter to renderButton .
To minimize user friction google.accounts.id.prompt() is called to display One Tap as a second alternative to using the button to sign-up or sign-in.
The GIS library parses the HTML doc for elements with an ID attribute set to g_id_onload , or class attributes containing g_id_signin . If a matching element is found, the button will also be rendered using HTML, regardless if you’ve also rendered the button in JavaScript. To avoid displaying the button twice, possibly with conflicting parameters do not include HTML elements matching these names in your HTML pages.
Credential handling
After user consent is given, Google returns a JSON Web Token (JWT) credential known as an ID token to either the user’s browser, or directly to a login endpoint hosted by your platform.
Where you choose to receive the JWT depends upon if you render the button using HTML or JavaScript and if popup or redirect UX mode is used.
Popup mode
Using popup UX mode performs the sign-in UX flow in a pop-up window. This is generally a less intrusive experience for users and is the default UX mode.
When rendering the button using:
HTML you can set either:
- data-callback to return the JWT to your callback handler, or
- data-login_uri for Google to send the JWT directly to your login endpoint using a POST request.
If both values are set, data-callback takes precedence over data-login_uri . For example, this may be useful when a callback handler is used during debugging.
JavaScript you must set callback , popup mode does not support redirects when rending the button in JavaScript. If set, login_uri is ignored.
See handle the returned credential response. for more on decoding the JWT within your JS callback handler.
Redirect mode
Using redirect UX mode performs the sign-in UX flow using full page redirection of the user’s browser, and Google returns the JWT directly to your login endpoint using a POST request. This is generally a more intrusive experience for users, but is considered to be the most secure sign-in method.
When rendering the button using:
- HTML optionally set data-login_uri to the URI of your login endpoint.
- JavaScript optionally set login_uri to the URI of your login endpoint.
If you do not provide a value, Google returns the JWT to the URI of the current page.
Your login endpoint URI
Use HTTPS and an absolute URI when setting data-login_uri or login_uri . For example, https://example.com/path .
HTTP is only allowed when using localhost during development: http://localhost/path .
Refer to Use secure JavaScript origins and redirect URIs for a full description of Google’s requirements and validation rules.
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.
Источник
Android sign in with google button
A custom SignInButton for Android that supports ‘android:text’ attribute, currently not supported by Google’s original ‘SignInButton’. This library also allows to set button theme to dark or light and is based on Google guidelines.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Problem
You want to add a Google Sign-In button to your Android application. But you want to change the text on the Google Sign-In button or provide custom localization? You would think setting android:text on the com.google.android.gms.common.SignInButton in your layout file would do the trick. However it turns out that that attribute is not available for SignInButton .
Solution
This library helps you add text to Google Sign-In Button easily using standard android:text attribute. It also allows you to set the button theme to dark or light using app:isDarkTheme=»true» attribute. It does so following Google’s guidelines to create sign-in button.
| Light Theme (White) | Dark Theme (Blue) |
|---|---|
Usage
Add the following to your app module level build.gradle file:
In your XML Layout, have the following:
Options
- app:isDarkTheme=»
» : To switch between blue theme and gray white for the button. The library handles changing of text color and background color. It also handles the change of color on button press or button clicks. - android:text=»
» : As usual to set the text on the button.
(dirty) Solutions
On the Stackoverflow, there are obviously questions which have been asked for this issue. One of them is Can I edit the text of sign in button on Google? Many of them suggest using «hacks» like finding the first TextView in the button or finding any TextView in the button. The issue with them is they might stop working if Google updates the implementation.
Google’s Suggestion
From documentation, Google suggests creating a custom button as mentioned on Customizing the Sign-In Button. Then it suggests using the branding guidelines as mentioned at Sign-In Branding Guidelines. It includes using custom icons and images int he button, setting text size to specifics, paddings and other do’s and don’ts for the logo.
Doing as per Google’s suggestion involves some custom work. This small 3.93 KB library does that for you. Please feel free to make pull requests to improve the library. I wanted to create a re-usable solution when I came across this problem while implementing the Sign-In button. Just wanted to share with everyone.
License
About
A custom SignInButton for Android that supports ‘android:text’ attribute, currently not supported by Google’s original ‘SignInButton’. This library also allows to set button theme to dark or light and is based on Google guidelines.
Источник