Flutter认证授权插件simple_auth_flutter的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter认证授权插件simple_auth_flutter的使用

简介

simple_auth_flutter 是一个用于Flutter应用的认证和授权插件,支持多种流行的OAuth2提供商(如Google、Facebook等)。这个插件简化了API调用中的认证流程,并且可以自动处理用户的登录和凭证缓存。

支持的提供者

  • Azure Active Directory
  • Amazon
  • Dropbox
  • Facebook
  • Github
  • Google
  • Instagram
  • Linked In
  • Microsoft Live Connect
  • Keycloak
  • 任何标准的OAuth2/Basic Auth服务器

使用示例

添加依赖

首先,在你的 pubspec.yaml 文件中添加 simple_auth_flutter 和其他必要的依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_auth_flutter: ^3.0.0

dev_dependencies:
  build_runner: ^1.0.0
  simple_auth_generator: ^3.0.0

运行 flutter pub get 来安装这些依赖。

初始化插件

在你的 main.dart 文件中初始化 SimpleAuthFlutter

import 'package:flutter/material.dart';
import 'package:simple_auth/simple_auth.dart' as simpleAuth;
import 'package:simple_auth_flutter/simple_auth_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SimpleAuthFlutter.init(context);
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

创建API实例并进行认证

以下是一个使用Google API进行用户认证的例子:

import 'package:simple_auth/simple_auth.dart' as simpleAuth;

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  final simpleAuth.GoogleApi googleApi = simpleAuth.GoogleApi(
    "google",
    "992461286651-k3tsbcreniknqptanrugsetiimt0lkvo.apps.googleusercontent.com",
    "redirecturl",
    clientSecret: "avrYAIxweNZwcHpsBlIzTp04",
    scopes: [
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/userinfo.profile"
    ],
  );

  void _incrementCounter() async {
    var profile = await googleApi.getUserProfile();
    print(profile.name);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You have pushed the button this many times:'),
            Text('$_counter', style: Theme.of(context).textTheme.headline4),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Android 配置

AndroidManifest.xml 中添加以下内容以处理重定向:

<activity android:name="clancey.simpleauth.simpleauthflutter.SimpleAuthCallbackActivity" >
    <intent-filter android:label="simple_auth">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="com.myapp.foo" />
    </intent-filter>
</activity>

iOS 配置

AppDelegate.m 中添加以下代码:

#import "SimpleAuthFlutterPlugin.h"

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [SimpleAuthFlutterPlugin checkUrl:url];
}

Info.plist 中添加以下内容:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.myapp.foo</string>
        </array>
        <key>CFBundleURLName</key>
        <string>myappredirect</string>
    </dict>
</array>

序列化与生成器

序列化

如果你希望自动序列化JSON对象,可以实现 JsonSerializable 接口或自定义转换器:

@GoogleApiDeclaration("GoogleTestApi","client_id",clientSecret: "client_secret", scopes: ["TestScope", "Scope2"])
abstract class GoogleTestDefinition {
  @Get(url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
  Future<Response<GoogleUser>> getCurrentUserInfo();
}

使用生成器

添加生成器依赖并在项目根目录下运行:

dev_dependencies:
  simple_auth_generator: 
  build_runner: ^0.8.0

然后运行:

flutter packages pub run build_runner build

更多关于Flutter认证授权插件simple_auth_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter认证授权插件simple_auth_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用 simple_auth_flutter 插件进行认证授权的 Flutter 代码示例。simple_auth_flutter 是一个流行的 Flutter 插件,用于处理各种认证流程,如 OAuth2、Apple Sign In、Google Sign In 等。

首先,你需要在你的 pubspec.yaml 文件中添加 simple_auth_flutter 依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_auth_flutter: ^x.y.z  # 请替换为最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,我们来看一个具体的代码示例,这里以 Google Sign In 为例:

  1. 配置 Google Sign In

android/app/src/main/AndroidManifest.xml 中添加以下权限和配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 添加以下权限 -->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        ... >
        <!-- 添加以下配置 -->
        <meta-data
            android:name="com.google.android.gms.client.measurement.ENABLED"
            android:value="true"/>
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Google Sign In Activity -->
        <activity
            android:name="com.google.android.gms.auth.api.signin.internal.SignInHubActivity"
            android:excludeFromRecents="true"
            android:exported="true"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
        <activity
            android:name="com.google.android.gms.auth.api.signin.internal.UserSelectingAccountActivity"
            android:excludeFromRecents="true"
            android:exported="true"/>
        <provider
            android:name="com.google.android.gms.auth.api.signin.internal.GoogleSignInMetadataProvider"
            android:authorities="${applicationId}.google_signin_metadata_provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_paths"/>
        </provider>
    </application>

</manifest>

ios/Runner/Info.plist 中添加 Google Sign In 配置(假设你已经有 GoogleService-Info.plist 文件):

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>YOUR_REVERSED_CLIENT_ID</string>
        </array>
    </dict>
</array>
<key>GoogleService-Info.plist</key>
<dict>
    <key>Type</key>
    <string>File</string>
    <key>Path</key>
    <string>GoogleService-Info.plist</string>
</dict>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>googlechrome</string>
    <string>com.google.chrome.ios</string>
    <string>com.google.ios.gms</string>
</array>
  1. Flutter 代码实现

在你的 Flutter 项目中,创建一个新的 Dart 文件,比如 auth_service.dart,并添加以下代码:

import 'package:flutter/material.dart';
import 'package:simple_auth_flutter/simple_auth_flutter.dart';

class AuthService {
  final SimpleAuth _auth = SimpleAuth();

  Future<void> googleSignIn() async {
    try {
      final result = await _auth.authorize(
        'google',
        clientId: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
        redirectUri: 'com.example.yourapp:/oauth2redirect',
        scopes: [
          'profile',
          'email',
        ],
      );

      if (result?.accessToken != null) {
        print('Google Sign In Success: ${result.accessToken}');
        // 在这里处理登录成功后的逻辑,比如保存 token 到本地
      } else {
        print('Google Sign In Failed');
      }
    } catch (e) {
      print('Google Sign In Error: $e');
    }
  }
}

确保将 YOUR_GOOGLE_CLIENT_ID 替换为你的实际 Google 客户端 ID。

  1. 使用 AuthService

在你的主应用代码中,比如 main.dart,添加按钮来触发 Google Sign In:

import 'package:flutter/material.dart';
import 'auth_service.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final AuthService _authService = AuthService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Google Sign In Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () => _authService.googleSignIn(),
            child: Text('Sign In with Google'),
          ),
        ),
      ),
    );
  }
}

这个示例展示了如何使用 simple_auth_flutter 插件进行 Google Sign In 的基本流程。你可以根据需要扩展这个示例,添加更多的认证方式或处理更多的认证结果。

回到顶部