📜  googlesign in flutter 的访问令牌 (1)

📅  最后修改于: 2023-12-03 15:15:24.790000             🧑  作者: Mango

Google Sign In in Flutter 的访问令牌

Google Sign In 是一种用于在 Flutter 应用程序中进行身份验证的方法。当用户使用他们的 Google 帐户登录应用程序时,应用程序会收到一个 OAuth2 访问令牌,该令牌可以用于访问用户帐户的受保护数据。本文将为您介绍如何使用 Google Sign In 来获取访问令牌,以及如何将其用于访问 Google API。

在Flutter中使用Google Sign In

在 Flutter 中使用 Google Sign In 需要进行一些设置,包括在您的 Google Cloud Console 中创建 OAuth2 客户端密钥和配置 Flutter 应用程序以与您的 Google 帐户进行身份验证。

创建 OAuth2 客户端密钥
  1. 前往 Google Cloud Console
  2. 在顶部菜单中选择项目并创建一个新项目
  3. 导航到 APIs 和 Services > Credential
  4. 点击"创建凭证"
  5. 选择 "OAuth客户端ID"
  6. 选择应用程序类型为 "移动应用",并填写包名和 SHA1 指纹信息
  7. 点击 "创建",然后复制您的客户端ID和客户端密钥
在Flutter应用程序中配置身份验证
  1. 添加google_sign_in依赖
dependencies:
  google_sign_in: ^4.5.1
  1. 实例化GoogleSignIn对象并验证用户身份
import 'package:google_sign_in/google_sign_in.dart';

final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ],
);

Future<void> _handleSignIn(BuildContext context) async {
  try {
    await _googleSignIn.signIn();
    // 获取访问令牌并将其用于访问Google API
    // ...
  } catch (error) {
    print(error);
  }
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Google Sign In Example'),
    ),
    body: Center(
      child: RaisedButton(
        onPressed: () => _handleSignIn(context),
        child: Text('Sign in with Google'),
      ),
    ),
  );
}
  1. 获取访问令牌并将其用于访问Google API
import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> _handleSignIn(BuildContext context) async {
  try {
    await _googleSignIn.signIn();
    final GoogleSignInAccount googleUser = _googleSignIn.currentUser;
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    final String accessToken = googleAuth.accessToken;
    // 使用访问令牌访问 Google API
    final response = await http.get(
      'https://www.googleapis.com/oauth2/v3/userinfo',
      headers: {'Authorization': 'Bearer $accessToken'},
    );
    final userInfo = json.decode(response.body);
    print(userInfo);
  } catch (error) {
    print(error);
  }
}
结论

Google Sign In 为 Flutter 开发人员提供了一种简单但强大的身份验证方法,可以轻松地与 Google API 一起使用。通过遵循本文中提供的步骤,在您的 Flutter 应用程序中使用 Google Sign In 来获得访问令牌,并使用它来访问 Google API。