Flutter Twitch认证插件unofficial_twitch_auth的使用

Flutter Twitch认证插件unofficial_twitch_auth的使用

该插件允许你使用最新的Twitch API来验证、撤销或认证你的客户端。

可以在pub.dev上查看:https://pub.dev/packages/unofficial_twitch_auth

功能

该插件包含以下方法:

  • getLoginLink: 用于获取登录链接。
  • validate: 终点/oauth2/validate 允许验证获取到的令牌。
  • revoke: 终点/oauth2/revoke 允许撤销令牌。

更多信息请参阅类 twitch_authentication.dart

在Twitch开发者控制台注册你的应用

  • 访问开发网站:https://dev.twitch.tv
  • 打开“您的控制台”
  • 使用名称、OAuth重定向和类别注册一个新的应用程序
  • 设置完成后,你会被重定向到你的应用。在这里你可以看到你的Client ID和秘密令牌(不要与任何人分享!)

开始使用

你可以使用Provider来获取实现实例:

List<SingleChildWidget> _initProvider() {
  return [
    ...
    Provider<TwitchAuthentication>(
      create: (ctx) => TwitchAuthenticationImpl(),
    ),
  ];
}

或者你可以使用get_it库来注册你的实例及其实现:

GetIt getIt = GetIt.instance;

void setup() {
  getIt.registerSingleton<TwitchAuthentication>(
      TwitchAuthenticationImpl()
  );
}

使用生成的实例来调用以下方法之一:

生成登录URL

final urlLogin = authInstance.getLoginLink(
    clientId: 'my_client_id', redirect: 'http://myredirecturl');

验证访问令牌

final validate = authInstance.validate(accessToken: 'zzz');

撤销访问令牌

final revoke = authInstance.revoke(clientId: 'my_client_id', accessToken: 'zzz');

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

1 回复

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


当然,以下是如何在Flutter项目中集成并使用unofficial_twitch_auth插件的示例代码。这个插件允许你通过OAuth2进行Twitch认证。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  unofficial_twitch_auth: ^最新版本号  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Twitch客户端ID和重定向URI

在Twitch开发者门户中创建一个应用,获取客户端ID(Client ID)和客户端密钥(Client Secret),并设置一个重定向URI(例如,yourapp://callback)。

3. 配置Android和iOS

Android

android/app/src/main/AndroidManifest.xml中添加一个intent-filter来处理重定向URI:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTop"
    android:theme="@style/LaunchTheme"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|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>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="yourapp" android:host="callback" />
    </intent-filter>
</activity>

iOS

ios/Runner/Info.plist中添加一个URL类型来处理重定向URI:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>yourapp</string>
        </array>
    </dict>
</array>

4. 使用插件进行认证

在你的Flutter代码中,你可以这样使用unofficial_twitch_auth插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TwitchAuthScreen(),
    );
  }
}

class TwitchAuthScreen extends StatefulWidget {
  @override
  _TwitchAuthScreenState createState() => _TwitchAuthScreenState();
}

class _TwitchAuthScreenState extends State<TwitchAuthScreen> {
  String? accessToken;
  String? userId;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Twitch Auth Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (accessToken != null && userId != null)
              Text('Authenticated! Access Token: $accessToken, User ID: $userId'),
            else
              ElevatedButton(
                onPressed: () => _authenticate(),
                child: Text('Authenticate with Twitch'),
              ),
          ],
        ),
      ),
    );
  }

  void _authenticate() async {
    final TwitchAuthConfig config = TwitchAuthConfig(
      clientId: '你的客户端ID',
      redirectUri: Uri.parse('yourapp://callback'),
      scopes: ['user:read:email'], // 你可以根据需要添加其他scope
    );

    try {
      final result = await TwitchAuth.authenticate(config: config);
      setState(() {
        accessToken = result.accessToken;
        userId = result.userId;
      });
    } catch (e) {
      print('Authentication failed: $e');
    }
  }
}

注意事项

  1. 确保你的重定向URI在Twitch开发者门户中正确配置,并且在你的应用中正确设置。
  2. 替换你的客户端ID为你在Twitch开发者门户中获得的客户端ID。
  3. 你可以根据需要调整scopes数组中的权限。

这段代码展示了如何在Flutter应用中集成并使用unofficial_twitch_auth插件进行Twitch认证。

回到顶部