Flutter认证授权插件dfapi_auth的使用

Flutter认证授权插件dfapi_auth的使用

dfapi_auth 是一个为Flutter应用提供dfapi认证功能的插件。通过使用该插件,您可以轻松地将认证机制集成到您的应用中。

使用方法

您可以通过包裹 DfApiAuth 小部件来将认证功能添加到您的应用中。DfApiAuth 需要一个类型为 DfApiAuthRequest 的参数。

// DfApiAuthRequest

class DfApiAuthRequest {
  final Widget child;
  final AuthConfig configuration;
  final Widget loginWidget;
  final Widget loadingWidget;
  final Widget splashWidget;
  Function(String, DfApiUserInfo) callBack;

  DfApiAuthRequest({
    @required this.child,
    @required this.configuration,
    this.loginWidget,
    this.loadingWidget,
    this.splashWidget,
    Function(String, DfApiUserInfo) callBack,
  }) : this.callBack = callBack;
}

DfApiAuthRequest 包含两个必需的参数:childconfiguration

Configuration:

AuthConfig 类型的配置对象,用于存储应用进行身份验证所需的服务端地址信息。

AuthConfig({
  @required String address,
  String loginPath = "auth/login",
  String refreshTokenPath = "auth/refreshToken",
  String logoutPath = "",
})
  • address 是必填项,表示进行认证操作的服务器地址。
  • 其他字段分别表示登录、刷新令牌和登出的路径,默认值基于假定有一个名为 AuthController 的控制器。

Child:

认证完成后将导航到的页面。例如,这可以是应用的主页面。

LoginWidget:

如果您希望自定义用户登录界面,可以使用 loginWidget 参数实现自定义设计。

默认和自定义示例屏幕

[图像] [图像]

加载和启动页

其他如 loadingWidgetsplashWidget 参数的工作原理与 loginWidget 相同,它们允许您完全自定义这些过程。如果不设置,则使用默认值。

CallBack

当用户登录后,如果需要获取token或用户信息,可以在 request 中传递一个 Function(String, DfApiUserInfo) 类型的回调函数。

child: DfApiApp(
  request: DfApiAuthRequest(
    ...
    callBack: apiHelperInitializer,
    ...
  ),
),

回调函数返回的token可以在API调用中使用。

void apiHelperInitializer(String token, DfApiUserInfo userInfo) {
  if (GetIt.I.isRegistered<ApiHelper>()) return;

  var uri = Uri.parse("api url");
  List<ApiHelperPathItem> paths = [
    ApiHelperPathItem.get("Key", "Path/SamplePath"),
  ];

  var apiHelper = ApiHelper.setup(
    uri,
    token,
    paths,
    responseResolverFunc: (json) => (json) { //... },
  );
  GetIt.I.registerLazySingleton<ApiHelper>(() => apiHelper);
}

可以使用 api_helper 包来进行API调用。

在不同位置获取用户信息或关联的token

如果在应用的不同位置需要访问登录用户的详细信息或相关token,可以使用 DfApiAppFunctions 类。该类可以通过 DfApiApp 中的 functions 属性访问。

var token = await DfApiApp.functions.getToken();
// 或者
token = DfApiApp.token;

基本使用

最基本的方式如下:

return MaterialApp(
  //...
  home: DfApiApp(
    request: DfApiAuthRequest(
      configuration: AuthConfig(address: "adress"),
      child: HomePage() // 认证后导航到的widget。
    )
  )
);

自定义使用

如果需要自定义,可以这样使用:

return MaterialApp(
  //...
  home: DfApiApp(
    request: DfApiAuthRequest(
      configuration: AuthConfig(
        address: "adress"
      ),
      child: HomePage(),
      loginWidget: LoginPage(),
      loadingWidget: Loading(),
      callBack: apiHelperInitializer,
    )
  )
);

示例代码

import 'package:dfapi_auth/dfapi_app.dart';
import 'package:dfapi_auth/models/auth_configuration.dart';
import 'package:dfapi_auth/models/dfapi_auth_request.dart';
import 'package:flutter/material.dart';

class App extends StatefulWidget {
  const App({Key? key}) : super(key: key);

  [@override](/user/override)
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  var demoIdentityServerConfig = AuthConfig(
    address: "https://demo.identityserver.io",
  );

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Container(
          child: DfApiApp(
            request: DfApiAuthRequest(
              child: Container(
                color: Colors.white,
                child: OutlinedButton(
                  onPressed: () {
                    DfApiApp.functions.logOut();
                  },
                  child: Text("Log Out"),
                ),
              ),
              configuration: demoIdentityServerConfig,
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


dfapi_auth 是一个用于 Flutter 应用的认证和授权插件,通常用于与后端 API 进行身份验证和授权的交互。以下是如何使用 dfapi_auth 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  dfapi_auth: ^版本号

请将 ^版本号 替换为最新的插件版本号。你可以通过 pub.dev 查找最新的版本。

2. 导入插件

在你的 Dart 文件中导入 dfapi_auth 插件:

import 'package:dfapi_auth/dfapi_auth.dart';

3. 初始化插件

在使用插件之前,通常需要对其进行初始化。这可能涉及到设置一些配置参数,如 API 的基础 URL、客户端 ID、客户端密钥等。

void main() {
  DFApiAuth.initialize(
    baseUrl: 'https://your-api-url.com',
    clientId: 'your-client-id',
    clientSecret: 'your-client-secret',
  );
  runApp(MyApp());
}

4. 用户登录

使用 DFApiAuth 进行用户登录。通常,你需要提供用户的用户名和密码。

Future<void> login(String username, String password) async {
  try {
    final response = await DFApiAuth.instance.login(
      username: username,
      password: password,
    );
    print('Login successful: ${response.accessToken}');
  } catch (e) {
    print('Login failed: $e');
  }
}

5. 获取访问令牌

登录成功后,你可以通过 DFApiAuth 获取访问令牌(access token),并将其用于后续的 API 请求。

Future<void> fetchData() async {
  try {
    final token = await DFApiAuth.instance.getAccessToken();
    final response = await http.get(
      Uri.parse('https://your-api-url.com/data'),
      headers: {
        'Authorization': 'Bearer $token',
      },
    );
    print('Data fetched: ${response.body}');
  } catch (e) {
    print('Failed to fetch data: $e');
  }
}

6. 刷新令牌

如果访问令牌过期,你可以使用刷新令牌来获取新的访问令牌。

Future<void> refreshToken() async {
  try {
    final response = await DFApiAuth.instance.refreshToken();
    print('Token refreshed: ${response.accessToken}');
  } catch (e) {
    print('Failed to refresh token: $e');
  }
}

7. 用户注销

当用户注销时,你可以清除当前的认证状态。

Future<void> logout() async {
  await DFApiAuth.instance.logout();
  print('User logged out');
}

8. 处理认证状态

你可以监听用户的认证状态,以便在用户登录或注销时更新 UI。

DFApiAuth.instance.authState.listen((state) {
  if (state == AuthState.authenticated) {
    print('User is authenticated');
  } else {
    print('User is not authenticated');
  }
});

9. 错误处理

确保在处理认证和授权时捕获并处理可能发生的错误。

try {
  final response = await DFApiAuth.instance.login(
    username: 'user',
    password: 'pass',
  );
} catch (e) {
  print('Error occurred: $e');
}
回到顶部