How to implement Google SignIn OAuth2 authentication in your App? - Android Studio Java | API 34
In this video it shows the steps to implement the OAuth2 authentication in your Android App. It refers the code from the Google developer documentation at - https://developers.google.com/identity/one-tap/android/get-saved-credentials.
It also shows the steps to create a new project in the Google's cloud platform and create OAuth2.0 credentials. Please note that for the implementation to work, one needs to create both web client and Android application type OAuth 2.0 credentials. Though the in the code only web application type client ID would be required for directing the authentication.
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: [email protected]
Complete source code and other details/ steps of this video are posted in the below link:
https://programmerworld.co/android/how-to-implement-google-signin-oauth2-authentication-client-id-in-your-app-android-studio-java-api34-android-14/
However, the main Java code is copied below also for reference:
package com.programmerworld.googleoauthauthenticationapp;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private SignInClient oneTapClient;
private BeginSignInRequest signInRequest;
private static final int REQ_ONE_TAP = 100;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
oneTapClient = Identity.getSignInClient(this);
signInRequest = BeginSignInRequest.builder()
.setPasswordRequestOptions(BeginSignInRequest.PasswordRequestOptions.builder()
.setSupported(true)
.build())
.setGoogleIdTokenRequestOptions(BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
// Your server's client ID, not your Android client ID.
.setServerClientId("553874834892-51tqjh0j2m0nren6789bj02h6t2bnquh.apps.googleusercontent.com") // TODO
// Only show accounts previously used to sign in.
.setFilterByAuthorizedAccounts(false)
.build())
// Automatically sign in when exactly one credential is retrieved.
.setAutoSelectEnabled(true)
.build();
}
public void buttonGoogleSignIn(View view){
oneTapClient.beginSignIn(signInRequest)
.addOnSuccessListener(this, new OnSuccessListener-BeginSignInResult-() {
@Override
public void onSuccess(BeginSignInResult result) {
try {
startIntentSenderForResult(
result.getPendingIntent().getIntentSender(), REQ_ONE_TAP,
null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Couldn't start One Tap UI: " + e.getLocalizedMessage());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// No saved credentials found. Launch the One Tap sign-up flow, or
// do nothing and continue presenting the signed-out UI.
Log.d(TAG, e.getLocalizedMessage());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_ONE_TAP:
try {
SignInCredential credential = oneTapClient.getSignInCredentialFromIntent(data);
String idToken = credential.getGoogleIdToken();
String username = credential.getId();
String password = credential.getPassword();
textView.setText("Authentication done.\nUsername is " + username);
if (idToken != null) {
// Got an ID token from Google. Use it to authenticate
// with your backend.
Log.d(TAG, "Got ID token.");
} else if (password != null) {
// Got a saved username and password. Use them to authenticate
// with your backend.
Log.d(TAG, "Got password.");
}
} catch (ApiException e) {
textView.setText(e.toString());
}
break;
}
}
}
--
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «How to implement Google SignIn OAuth2 authentication in your App? - Android Studio Java | API 34», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.