google_sign_in_web_redirect

实现 Google 登录重定向 (适用于隐身模式)。

用法

导入包

dependencies:
  google_sign_in_web_redirect:
    git: https://github.com/kunkaamd/google_sign_in_web_redirect
import 'package:google_sign_in_web_redirect/google_sign_in_web_redirect.dart';

集成

首先,请按照 此处的 说明创建您的 Google 登录 OAuth 客户端 ID。

在您的 web/index.html 文件中,将以下 meta 标签添加到文档的 head 部分的某个位置:

<meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">

为了使此客户端正常工作,最后一步是配置 **授权的 JavaScript 源**,它*识别您的应用程序可以发送 API 请求的域*。在本地开发时,这通常是 localhost 和某个端口。

您可以通过以下方式完成此操作:

  1. 访问 凭据页面
  2. 点击您上面创建的 OAuth 2.0 Web 应用程序客户端的“编辑”。
  3. 在 **授权的 JavaScript 源** 中添加您想要的 URI。
  4. 在 **授权的重定向 URI** 中添加重定向 URI。

对于本地开发,您可以添加一个 localhost 条目,例如:https://:7357

https://:7357 启动 Flutter

通常,flutter run 会在一个随机端口上启动。如果需要处理上述之类的身份验证,这并不是最合适的行为。

您可以通过以下方式告知 flutter run 在特定的主机和端口上侦听请求:

flutter run -d chrome --web-hostname localhost --web-port 7357

其他 API

如果您需要添加额外的 API(例如 Google People API),请阅读其余说明。

使用插件

将以下导入添加到您的 Dart 代码中

void main() {
  GoogleSignWeb.getQueryParameters();///make sure add this line
  setPathUrlStrategy();///this package only support PathUrl
  runApp(const MyApp());
}

解决带有查询参数的“无对应路由”问题

onGenerateRoute: (settings) {
  if (settings.name?.contains("/login") ?? false) {
    return MaterialPageRoute(
      builder: (_) => const LoginScreen(),
    );
  }
  return null;
},

可用范围的完整列表.

现在您可以使用 GoogleSignWeb 类在 Dart 代码中进行身份验证,例如:

  initGoogleSignIn() async {
    if(kIsWeb) {
      GoogleSignWeb.init(
        ///id_token if you only want get user_id
        ///code if you need basic profile, access_token
        responseType: "code",
        scopes: ['email', 'profile'],
      );
      if(GoogleSignWeb.instance?.queryParameters?.idToken != null) {
        final jwt = await GoogleSignWeb.instance!.verifyToken();
        final userId = jwt.sub;
        Navigator.pushNamed(context, '/main',arguments: userId);
      } else if (GoogleSignWeb.instance?.queryParameters?.code != null) {
        ///TODO step 1: send code to Server side to take ID Token & basic profile(name, displayname, picture)
        /// we can't make this api from Client side because you need client_secret.
        /// POST /token HTTP/1.1
        /// Host: oauth2.googleapis.com
        /// Content-Type: application/x-www-form-urlencoded
        ///
        /// code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
        /// client_id=your-client-id&
        /// client_secret=your-client-secret&
        /// redirect_uri=https%3A//oauth2.example.com/code&
        /// grant_type=authorization_code
        /// more details: https://developers.google.com/identity/protocols/oauth2/openid-connect#exchangecode
        ///
        ///TODO step 2: verify token get from response Server side
        ///
        /// GoogleSignWeb.instance.token = "YOUR_ID_TOKEN_RESPONSE_FROM_SERVER";
        /// GoogleSignWeb.instance.verifyToken();

        try {
          final response = await http.post(Uri.parse("https://six-colts-rhyme-116-110-109-131.loca.lt/auth/idToken"),body: {
            "code":  GoogleSignWeb.instance!.queryParameters!.code,
          },headers: {
            "Access-Control_Allow_Origin": "*"
          });
          final responseData = jsonDecode(response.body);
          GoogleSignWeb.instance!.token = responseData['id_token'];
          /// final accessToken = responseData['access_token'];
          final jwt = await GoogleSignWeb.instance!.verifyToken();
          Navigator.pushNamed(context, '/main',arguments: jwt.name);
        } catch (_) {
          print(_.toString());
        }
      }
    }
  }

//on press login;
GoogleSignWeb.instance?.signIn();

示例

google_sign_in_web_redirect 中查找示例连接。

谢谢!

GitHub

查看 Github