如何使用颤振在 django 中进行 google、facebook 身份验证

Posted

技术标签:

【中文标题】如何使用颤振在 django 中进行 google、facebook 身份验证【英文标题】:How to make google, facebook authentication in django with flutter 【发布时间】:2021-02-04 18:16:41 【问题描述】:

我将 Flutter 用于移动应用,将 django 用于后端 API。我希望用户能够使用来自 Facebook、Google 等的帐户登录。我该如何实现呢?

我还看到 dj-rest-auth 提供社交媒体身份验证请求。我应该使用这样的东西吗?

【问题讨论】:

dj-rest-auth 建立在 all-auth 之上,它支持大量社交登录和 JWT 令牌。所以是的,这是一个不错的选择。 你找到答案了吗?您标记为正确的答案对我来说似乎不正确 【参考方案1】:

尝试使用 jwt,它是 JSON 网络令牌

【讨论】:

【参考方案2】:

有flutter_facebook_login 包。你可以这样使用它:


import 'package:flutter_facebook_login/flutter_facebook_login.dart';

final facebookLogin = FacebookLogin();
final result = await facebookLogin.logInWithReadPermissions(['email']);

switch (result.status) 
  case FacebookLoginStatus.loggedIn:
    _sendTokenToServer(result.accessToken.token);
    _showLoggedInUI();
    break;
  case FacebookLoginStatus.cancelledByUser:
    _showCancelledMessage();
    break;
  case FacebookLoginStatus.error:
    _showErrorOnUI(result.errorMessage);
    break;


还有google_sign_in 包用于您问题的另一部分。这是complete example:


// Copyright 2019 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:convert' show json;

import "package:http/http.dart" as http;
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

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

void main() 
  runApp(
    MaterialApp(
      title: 'Google Sign In',
      home: SignInDemo(),
    ),
  );


class SignInDemo extends StatefulWidget 
  @override
  State createState() => SignInDemoState();


class SignInDemoState extends State<SignInDemo> 
  GoogleSignInAccount _currentUser;
  String _contactText;

  @override
  void initState() 
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) 
      setState(() 
        _currentUser = account;
      );
      if (_currentUser != null) 
        _handleGetContact();
      
    );
    _googleSignIn.signInSilently();
  

  Future<void> _handleGetContact() async 
    setState(() 
      _contactText = "Loading contact info...";
    );
    final http.Response response = await http.get(
      'https://people.googleapis.com/v1/people/me/connections'
      '?requestMask.includeField=person.names',
      headers: await _currentUser.authHeaders,
    );
    if (response.statusCode != 200) 
      setState(() 
        _contactText = "People API gave a $response.statusCode "
            "response. Check logs for details.";
      );
      print('People API $response.statusCode response: $response.body');
      return;
    
    final Map<String, dynamic> data = json.decode(response.body);
    final String namedContact = _pickFirstNamedContact(data);
    setState(() 
      if (namedContact != null) 
        _contactText = "I see you know $namedContact!";
       else 
        _contactText = "No contacts to display.";
      
    );
  

  String _pickFirstNamedContact(Map<String, dynamic> data) 
    final List<dynamic> connections = data['connections'];
    final Map<String, dynamic> contact = connections?.firstWhere(
      (dynamic contact) => contact['names'] != null,
      orElse: () => null,
    );
    if (contact != null) 
      final Map<String, dynamic> name = contact['names'].firstWhere(
        (dynamic name) => name['displayName'] != null,
        orElse: () => null,
      );
      if (name != null) 
        return name['displayName'];
      
    
    return null;
  

  Future<void> _handleSignIn() async 
    try 
      await _googleSignIn.signIn();
     catch (error) 
      print(error);
    
  

  Future<void> _handleSignOut() => _googleSignIn.disconnect();

  Widget _buildBody() 
    if (_currentUser != null) 
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            leading: GoogleUserCircleAvatar(
              identity: _currentUser,
            ),
            title: Text(_currentUser.displayName ?? ''),
            subtitle: Text(_currentUser.email ?? ''),
          ),
          const Text("Signed in successfully."),
          Text(_contactText ?? ''),
          RaisedButton(
            child: const Text('SIGN OUT'),
            onPressed: _handleSignOut,
          ),
          RaisedButton(
            child: const Text('REFRESH'),
            onPressed: _handleGetContact,
          ),
        ],
      );
     else 
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text("You are not currently signed in."),
          RaisedButton(
            child: const Text('SIGN IN'),
            onPressed: _handleSignIn,
          ),
        ],
      );
    
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: const Text('Google Sign In'),
        ),
        body: ConstrainedBox(
          constraints: const BoxConstraints.expand(),
          child: _buildBody(),
        ));
  


【讨论】:

Akif 非常感谢你,如果你知道(或写过)关于这个主题的任何文章或教程,如果你分享链接会很棒。具体来说,我需要详细了解如何在没有 Firebase 的情况下将 google auth 与 Flutter 一起使用。

以上是关于如何使用颤振在 django 中进行 google、facebook 身份验证的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 中使用 Google API?

如何在颤振/飞镖中捕获平台异常?

如何为 Google Play 商店签署我的颤振应用程序?

你如何在颤振飞镖中渲染脚本标签

如何解决颤振包 google_mobile_ads 中的此错误

如何使用增强现实在颤振中创建面部应用程序