Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Añadir Google Sign Auth en Flutter

Tiempo de lectura: 4 minutos

Hoy vamos a aprender cómo podemos implementar la autenticación con Google en nuestra APP de Flutter.


Vamos a Google Cloud Platform (https://cloud.google.com/) y pulsamos en Consola

Ahora seleccionamos nuestro proyecto (si ya lo tenemos creado por Firebase) o creamos uno nuevo.

Ahora buscamos: oauth clients

Elegimos External:

Rellenamos el nombre de la aplicación y los datos solicitados:

Después rellenamos Información de contacto del desarrollador:

Pulsamos en guardar y continuar.

En la siguiente pantalla no tocamos nada y volvemos a pulsar en guardar y continuar.

Lo mismo para la información opcional.

Ahora tenemos que añadir las claves permitidas, para ello vamos a Credenciales

Pulsamos en Crear Credenciales y Elegimos ID de cliente de OAuth

Elegimos tipo Android.

Añadimos el id de paquete que lo podemos encontrar en Android/app/build.gradle

Añadimos la clave SHA1 con el comando.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd android
./gradlew signingReport
cd android ./gradlew signingReport
cd android
./gradlew signingReport

Y nos devolverá la clave o claves que tengamos configuradas.

Tendremos que añadir la de debug y también release (si la tienes) (Aquí te indico cómo puedes crear una https://devcodelight.com/generar-un-apk-aab-release-con-flutter-y-visual-stuido-code/), si no tienes la de release, no importa, puedes probar primero con debug.

Copiamos la salida que pone SHA1:

Ahora se añade el código de Flutter:

  1. Ir a pubspec-yaml y añadir la dependencia:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
google_sign_in: ^6.2.1
google_sign_in: ^6.2.1
  google_sign_in: ^6.2.1

2. Crear el Widget que maneja el login Google:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'dart:convert';
import 'dart:async';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import '../../componentes/Boton_juego.dart';
import '../../internacionalizacion/AppLocalizations.dart';
import '../../utils/Constantes/Colors.dart';
const List<String> scopes = <String>['email'];
GoogleSignIn _googleSignIn = GoogleSignIn(
scopes: scopes,
);
class LoginGoogle extends StatefulWidget {
const LoginGoogle({Key? key});
@override
State createState() => _LoginGoogle();
}
class _LoginGoogle extends State<LoginGoogle> {
GoogleSignInAccount? _currentUser;
bool _isAuthorized = false;
String _contactText = '';
@override
void initState() {
super.initState();
_googleSignIn.onCurrentUserChanged
.listen((GoogleSignInAccount? account) async {
bool isAuthorized = account != null;
if (kIsWeb && account != null) {
isAuthorized = await _googleSignIn.canAccessScopes(scopes);
}
setState(() {
_currentUser = account;
_isAuthorized = isAuthorized;
});
if (isAuthorized) {
//Obten el email
print("Email: " + account!.email);
//Obten el nombre
print("Nombre: " + account.displayName!);
//Obten la foto
print("Foto: " + account.photoUrl!);
//Obten el id
print("Id: " + account.id);
//Obten el token
final GoogleSignInAuthentication auth = await account.authentication;
print("Token: " + auth.accessToken!);
//OAuth Token
print("OAuth Token: " + (auth.idToken ?? ""));
}
});
_googleSignIn.signInSilently();
}
Future<void> _handleSignIn() async {
try {
await _googleSignIn.signIn();
} catch (error) {
print('Error during Google Sign-In: $error');
}
}
Future<void> _handleSignOut() async {
if (_googleSignIn.currentUser != null) {
await _googleSignIn.disconnect();
}
}
@override
Widget build(BuildContext context) {
return TextButton(
style: TextButton.styleFrom(
backgroundColor: ColorsApp.blanco,
elevation: 5,
shadowColor: ColorsApp.rojo,
minimumSize: Size.fromWidth(150), // Ajusta el ancho mínimo según tus necesidades
),
onPressed: () {
_handleSignIn();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.g_mobiledata,
color: ColorsApp.rojo,
),
SizedBox(width: 8),
Text(
Traducir.of(context)!.translate("login.login_google"),
style: TextStyle(color: ColorsApp.rojo),
),
],
),
);
}
}
import 'dart:convert'; import 'dart:async'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart' show kIsWeb; import '../../componentes/Boton_juego.dart'; import '../../internacionalizacion/AppLocalizations.dart'; import '../../utils/Constantes/Colors.dart'; const List<String> scopes = <String>['email']; GoogleSignIn _googleSignIn = GoogleSignIn( scopes: scopes, ); class LoginGoogle extends StatefulWidget { const LoginGoogle({Key? key}); @override State createState() => _LoginGoogle(); } class _LoginGoogle extends State<LoginGoogle> { GoogleSignInAccount? _currentUser; bool _isAuthorized = false; String _contactText = ''; @override void initState() { super.initState(); _googleSignIn.onCurrentUserChanged .listen((GoogleSignInAccount? account) async { bool isAuthorized = account != null; if (kIsWeb && account != null) { isAuthorized = await _googleSignIn.canAccessScopes(scopes); } setState(() { _currentUser = account; _isAuthorized = isAuthorized; }); if (isAuthorized) { //Obten el email print("Email: " + account!.email); //Obten el nombre print("Nombre: " + account.displayName!); //Obten la foto print("Foto: " + account.photoUrl!); //Obten el id print("Id: " + account.id); //Obten el token final GoogleSignInAuthentication auth = await account.authentication; print("Token: " + auth.accessToken!); //OAuth Token print("OAuth Token: " + (auth.idToken ?? "")); } }); _googleSignIn.signInSilently(); } Future<void> _handleSignIn() async { try { await _googleSignIn.signIn(); } catch (error) { print('Error during Google Sign-In: $error'); } } Future<void> _handleSignOut() async { if (_googleSignIn.currentUser != null) { await _googleSignIn.disconnect(); } } @override Widget build(BuildContext context) { return TextButton( style: TextButton.styleFrom( backgroundColor: ColorsApp.blanco, elevation: 5, shadowColor: ColorsApp.rojo, minimumSize: Size.fromWidth(150), // Ajusta el ancho mínimo según tus necesidades ), onPressed: () { _handleSignIn(); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.g_mobiledata, color: ColorsApp.rojo, ), SizedBox(width: 8), Text( Traducir.of(context)!.translate("login.login_google"), style: TextStyle(color: ColorsApp.rojo), ), ], ), ); } }
import 'dart:convert';
import 'dart:async';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

import '../../componentes/Boton_juego.dart';
import '../../internacionalizacion/AppLocalizations.dart';
import '../../utils/Constantes/Colors.dart';

const List<String> scopes = <String>['email'];

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: scopes,
);

class LoginGoogle extends StatefulWidget {
  const LoginGoogle({Key? key});

  @override
  State createState() => _LoginGoogle();
}

class _LoginGoogle extends State<LoginGoogle> {
  GoogleSignInAccount? _currentUser;
  bool _isAuthorized = false;
  String _contactText = '';

  @override
  void initState() {
    super.initState();

    _googleSignIn.onCurrentUserChanged
        .listen((GoogleSignInAccount? account) async {
      bool isAuthorized = account != null;
      if (kIsWeb && account != null) {
        isAuthorized = await _googleSignIn.canAccessScopes(scopes);
      }

      setState(() {
        _currentUser = account;
        _isAuthorized = isAuthorized;
      });

      if (isAuthorized) {
        //Obten el email
        print("Email: " + account!.email);
        //Obten el nombre
        print("Nombre: " + account.displayName!);
        //Obten la foto
        print("Foto: " + account.photoUrl!);
        //Obten el id
        print("Id: " + account.id);
        //Obten el token
        final GoogleSignInAuthentication auth = await account.authentication;
        print("Token: " + auth.accessToken!);
        //OAuth Token
        print("OAuth Token: " + (auth.idToken ?? ""));
      }
    });

    _googleSignIn.signInSilently();
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch (error) {
      print('Error during Google Sign-In: $error');
    }
  }

  Future<void> _handleSignOut() async {
    if (_googleSignIn.currentUser != null) {
      await _googleSignIn.disconnect();
    }
  }

  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: TextButton.styleFrom(
        backgroundColor: ColorsApp.blanco,
        elevation: 5,
        shadowColor: ColorsApp.rojo,
        minimumSize: Size.fromWidth(150), // Ajusta el ancho mínimo según tus necesidades
      ),
      onPressed: () {
        _handleSignIn();
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.g_mobiledata,
            color: ColorsApp.rojo,
          ),
          SizedBox(width: 8),
          Text(
            Traducir.of(context)!.translate("login.login_google"),
            style: TextStyle(color: ColorsApp.rojo),
          ),
        ],
      ),
    );
  }
}

Importante: este es el token que debemos validar con el back:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print("OAuth Token: " + (auth.idToken ?? ""));
print("OAuth Token: " + (auth.idToken ?? ""));
print("OAuth Token: " + (auth.idToken ?? ""));

Recuerda añadir el código en:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
GoogleSignIn _googleSignIn = GoogleSignIn(
clientId:
'your_app_id.apps.googleusercontent.com',
scopes: scopes,
);
GoogleSignIn _googleSignIn = GoogleSignIn( clientId: 'your_app_id.apps.googleusercontent.com', scopes: scopes, );
GoogleSignIn _googleSignIn = GoogleSignIn(
  clientId:
      'your_app_id.apps.googleusercontent.com',
  scopes: scopes,
);

Para mostrar el botón de inicio de sesión:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
LoginGoogle(),
LoginGoogle(),
LoginGoogle(),

Importante, una vez creado el código Dart, tenemos que modificar la carpeta android.

Para ello vamos a android/build.gradle y añadimos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
dependencies {
...
classpath 'com.google.gms:google-services:4.3.8'
}
dependencies { ... classpath 'com.google.gms:google-services:4.3.8' }
 dependencies {
        ...
        classpath 'com.google.gms:google-services:4.3.8'
    }

Quedando de esta forma:

Y ahora vamos a android/app/build.gradle y añadimos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.gms.google-services'

Quedando de esta forma:

Luego tenemos que configurar iOS, para ello vamos al archivo info.plist y añadimos:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>com.googleusercontent.apps.YOUR_CLIENT_ID</string>
</array>
</dict>
</array>
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>com.googleusercontent.apps.YOUR_CLIENT_ID</string> </array> </dict> </array>
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>com.googleusercontent.apps.YOUR_CLIENT_ID</string>
    </array>
  </dict>
</array>

Indicando correctamente el Client ID: com.googleusercontent.apps.YOUR_CLIENT_ID

0

1 comentario en «Añadir Google Sign Auth en Flutter»

Deja un comentario