错误:Facebook 身份验证对此用户无效。使用 Back4App 进行颤振

Posted

技术标签:

【中文标题】错误:Facebook 身份验证对此用户无效。使用 Back4App 进行颤振【英文标题】:Error: Facebook auth is invalid for this user. Flutter using Back4App 【发布时间】:2021-10-17 20:34:13 【问题描述】:

我正在尝试使用 Back4App 通过 Facebook 创建登录方法 我一直在关注this instructions 并且我按照提供的所有内容做了所有事情,但是当我尝试对此进行测试时,它会抛出错误Status Code: 101 Error: Facebook auth is invalid for this user. 我的代码:(它与示例中提供的代码相同)

import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

void main() async 
  WidgetsFlutterBinding.ensureInitialized();

  final keyApplicationId = 'WHv1tAs6CNFngWtEG6zgX6LrwFCB*******';
  final keyClientKey = 'qn7DXL5FHSFJOYRzQLVJ0K4xl1fwS1*******';
  final keyParseServerUrl = 'https://parseapi.back4app.com';

  await Parse().initialize(keyApplicationId, keyParseServerUrl,
      clientKey: keyClientKey, debug: true);

  if (kIsWeb) 
    // initialiaze the facebook javascript SDK
    FacebookAuth.i.webInitialize(
      appId: "22079360*******", //<-- YOUR APP_ID
      cookie: true,
      xfbml: true,
      version: "v9.0",
    );
  

  runApp(MyApp());


class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      title: 'Flutter - Sign In with Facebook',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  


class HomePage extends StatefulWidget 
  @override
  _HomePageState createState() => _HomePageState();


class _HomePageState extends State<HomePage> 
  bool isLoggedIn = false;

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter - Sign In with Facebook'),
        ),
        body: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Container(
                  height: 200,
                  child: Image.network(
                      'http://blog.back4app.com/wp-content/uploads/2017/11/logo-b4a-1-768x175-1.png'),
                ),
                Center(
                  child: const Text('Flutter on Back4App',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                ),
                SizedBox(
                  height: 100,
                ),
                Container(
                  height: 50,
                  child: ElevatedButton(
                    child: const Text('Sign In with Facebook'),
                    onPressed: isLoggedIn ? null : () => doSignInFacebook(),
                  ),
                ),
                SizedBox(
                  height: 16,
                ),
                Container(
                  height: 50,
                  child: OutlinedButton(
                    child: const Text('Logout'),
                    onPressed: !isLoggedIn ? null : () => doUserLogout(),
                  ),
                )
              ],
            ),
          ),
        ));
  

  void showSuccess(String message) 
    showDialog(
      context: context,
      builder: (BuildContext context) 
        return AlertDialog(
          title: const Text("Success!"),
          content: Text(message),
          actions: <Widget>[
            new TextButton(
              child: const Text("OK"),
              onPressed: () 
                Navigator.of(context).pop();
              ,
            ),
          ],
        );
      ,
    );
  

  void showError(String errorMessage) 
    showDialog(
      context: context,
      builder: (BuildContext context) 
        return AlertDialog(
          title: const Text("Error!"),
          content: Text(errorMessage),
          actions: <Widget>[
            new TextButton(
              child: const Text("OK"),
              onPressed: () 
                Navigator.of(context).pop();
              ,
            ),
          ],
        );
      ,
    );
  

  void doSignInFacebook() async 
    try 
      //Check if the user is logged.
      final AccessToken? currentAccessToken =
          await FacebookAuth.instance.accessToken;
      if (currentAccessToken != null) 
        //Logout
        await FacebookAuth.instance.logOut();
      

      //Make a Login request
      final LoginResult result = await FacebookAuth.instance.login();

      if (result.status != LoginStatus.success) 
        showError(result.message!);
        return;
      

      final AccessToken accessToken = result.accessToken!;

      //https://docs.parseplatform.org/parse-server/guide/#facebook-authdata
      //According to the documentation, we must send a Map with user authentication data.
      final Map<String, dynamic> authData = <String, dynamic>;
      authData['id'] = accessToken.userId;
      authData['token'] = accessToken.token;
      authData['expiration_date'] = accessToken.expires.toString();

      final userData = await FacebookAuth.instance.getUserData();
      //Make sign in with Facebook
      final parseResponse = await ParseUser.loginWith('facebook', authData);

      if (parseResponse.success) 
        final ParseUser parseUser = parseResponse.result as ParseUser;

        //Additional Information in User
        if (userData.containsKey('email')) 
          parseUser.emailAddress = userData['email'];
        
        if (userData.containsKey('name')) 
          parseUser.set<String>('name', userData['name']);
        
        if (userData["picture"]["data"]["url"] != null) 
          parseUser.set<String>('photoURL', userData["picture"]["data"]["url"]);
        

        await parseUser.save();
        showSuccess("User was successfully with Sign In Facebook!");
        setState(() 
          isLoggedIn = true;
        );
       else 
        showError(parseResponse.error!.message);
      
     on Exception catch (e) 
      print(e.toString());
      showError(e.toString());
    
  

  void doUserLogout() async 
    final user = await ParseUser.currentUser() as ParseUser;
    var response = await user.logout();

    if (response.success) 
      showSuccess("User was successfully logout!");
      setState(() 
        isLoggedIn = false;
      );
     else 
      showError(response.error!.message);
    
  

调试控制台:

I/flutter ( 9901):
I/flutter ( 9901):  https://parseapi.back4app.com/users
I/flutter ( 9901): ╰--
I/flutter ( 9901): ╭-- Parse Response
I/flutter ( 9901): Class: _User
I/flutter ( 9901): Function: ParseApiRQ.loginWith
I/flutter ( 9901): Status Code: 101
I/flutter ( 9901): Type: ObjectNotFound
I/flutter ( 9901): Error: Facebook auth is invalid for this user.
I/flutter ( 9901): ╰--

颤振版本:2.2.2. parse_server_sdk: ^3.1.0 flutter_facebook_auth: ^3.5.0

【问题讨论】:

【参考方案1】:

back4app的文档中提供的代码有问题,您可以在the package's documentation找到正确的方法将信息发送到解析服务器 之前:

final parseResponse = await ParseUser.loginWith('facebook', authData);

之后:

final parseResponse = await ParseUser.loginWith('facebook',
      facebook(accessToken.token, accessToken.userId, accessToken.expires));

【讨论】:

以上是关于错误:Facebook 身份验证对此用户无效。使用 Back4App 进行颤振的主要内容,如果未能解决你的问题,请参考以下文章

错误社交身份验证 4.4:: 无效范围:publish_stream。

是否使用 google/facebook/twitter 身份验证登录?还是授权?

使用 Facebook Graph API 提取用户信息时出现身份验证错误

API 无效的随机 Facebook iOS SDK 身份验证令牌

Node.js E00007 Authorize.net 错误 - 由于身份验证值无效,用户身份验证失败

原版论坛 Facebook 身份验证错误:需要唯一 ID