You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中实现Credential Management API?浏览器端调用该API存谷歌登录凭证

在Flutter中实现Credential Management API

Flutter Web 端实现

Credential Management API是浏览器原生Web API,Flutter Web可通过dart:js包直接调用:

  1. 检查API可用性
import 'dart:js' as js;

bool isCredentialApiSupported() {
  return js.context.hasProperty('CredentialsContainer');
}
  1. 保存凭证(密码/联邦凭证)
void saveCredential(String username, String password) {
  if (!isCredentialApiSupported()) return;
  
  final credential = js.JsObject.jsify({
    'type': 'password',
    'id': username,
    'password': password
  });
  
  js.context['navigator']['credentials']['store'](credential).then((_) {
    // 保存成功后的逻辑处理
  }).catchError((error) {
    // 错误处理
  });
}
  1. 获取已保存的凭证
Future<void> getSavedCredential() async {
  if (!isCredentialApiSupported()) return;
  
  final credential = await js.promiseToFuture(
    js.context['navigator']['credentials']['get'](js.JsObject.jsify({
      'password': true,
      'federated': {'providers': ['https://accounts.google.com']}
    }))
  );
  
  if (credential != null) {
    final username = credential['id'];
    final password = credential['password'];
    // 自动登录逻辑
  }
}

Flutter 移动端实现

移动端(Android/iOS)无原生Credential Management API,推荐以下替代方案:

  • 使用flutter_secure_storage插件安全存储凭证:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

final storage = FlutterSecureStorage();

// 保存凭证
await storage.write(key: 'username', value: 'your_username');
await storage.write(key: 'password', value: 'your_password');

// 获取凭证
String? username = await storage.read(key: 'username');
String? password = await storage.read(key: 'password');
  • 集成谷歌账号登录可使用google_sign_in插件,登录后将用户凭证(如ID Token)存入安全存储。

浏览器中调用Credential Management API保存至谷歌

需使用**联邦凭证(Federated Credentials)**类型,以下是原生JavaScript实现:

  1. 检查API支持
if (!window.CredentialsContainer) {
  console.log('当前浏览器不支持Credential Management API');
  return;
}
  1. 保存谷歌联邦凭证
    在谷歌登录成功后调用:
async function saveGoogleCredential(googleUser) {
  const credential = new FederatedCredential({
    id: googleUser.getId(),
    name: googleUser.getBasicProfile().getName(),
    avatarURL: googleUser.getBasicProfile().getImageUrl(),
    provider: 'https://accounts.google.com'
  });
  
  try {
    await navigator.credentials.store(credential);
    console.log('谷歌凭证保存成功');
  } catch (error) {
    console.error('保存失败:', error);
  }
}
  1. 获取已保存的谷歌凭证
async function getGoogleCredential() {
  const credential = await navigator.credentials.get({
    federated: {
      providers: ['https://accounts.google.com']
    }
  });
  
  if (credential) {
    console.log('获取到谷歌凭证:', credential.id);
    // 自动登录逻辑
  }
}

注意:

  • 需在HTTPS环境下使用(localhost除外)
  • 需先集成Google Sign-In SDK获取用户实例,再保存联邦凭证

内容的提问来源于stack exchange,提问作者Hari .S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:40:23