Flutter身份验证插件okta_oidc的使用

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

Flutter身份验证插件okta_oidc的使用

okta_oidc 是一个用于简化移动应用中身份验证集成的Flutter插件。本文将详细介绍如何安装和使用该插件,包括必要的配置步骤和示例代码。

安装

要将 okta_oidc 添加到您的Flutter项目,请参考官方安装指南。以下是针对Android和iOS平台的一些特定要求:

Android

  1. 确保在 android/app/build.gradle 文件中设置 minSdkVersion 为21或更高:
    android {
      minSdkVersion 21
      ...
    }
    
  2. 添加重定向方案以接收来自Web浏览器的登录结果:
    manifestPlaceholders = [
        appAuthRedirectScheme: 'Add redirect schema here...'
    ]
    

iOS

  1. Podfile 中设置最低部署目标为13或更高:
    platform :ios, '13.0'
    

此外,您需要在项目的根目录下创建一个名为 assets/okta_config.json 的文件,并填入以下数据:

{
  "client_id": "",
  "redirect_uri": "",
  "end_session_redirect_uri": "",
  "scopes": [],
  "discovery_uri": ""
}

示例方法

初始化Okta (initOkta)

此方法使用配置文件或映射数据初始化Okta。

import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';

OktaOidc oktaOidc = OktaOidc();

Future<void> initOkta() async {
  final String response = await rootBundle.loadString('assets/okta_config.json');
  Map<String, dynamic>? oktaConfig = jsonDecode(response);
  oktaOidc.initOkta(oktaConfig);
}

登录 (login)

此方法会重定向至Okta登录页面,并返回响应或错误。

oktaOidc.login().then((value) {}).catchError((onError) {});

社交登录 (socialLogin)

可用于LinkedIn、Google和Apple等社交登录,需提供身份提供商和范围。

oktaOidc.socialLogin({
  "idp": "Add idp here...",
  "idp-scope": "Add scope here..."
}).then((value) {});

获取访问令牌 (getAccessToken)

如果已登录,则返回访问令牌;如果令牌过期,则刷新令牌。

oktaOidc.getAccessToken();

获取用户资料 (getUserProfile)

返回用户资料数据。

oktaOidc.getUserProfile();

注销 (logout)

清除用户会话。

oktaOidc.logout();

示例Demo

以下是一个完整的示例应用结构,展示了如何使用上述方法:

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Okta OIDC Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  [@override](/user/override)
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  late OktaOidc _oktaOidc;

  [@override](/user/override)
  void initState() {
    super.initState();
    _initializeOkta();
  }

  Future<void> _initializeOkta() async {
    // 初始化Okta OIDC
    final String config = await DefaultAssetBundle.of(context).loadString('assets/okta_config.json');
    _oktaOidc = OktaOidc();
    await _oktaOidc.initOkta(jsonDecode(config));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Okta OIDC Demo')),
      body: Center(child: Text('Hello, Okta!')),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用okta_oidc插件进行身份验证的代码示例。这个插件允许你与Okta的OpenID Connect(OIDC)服务集成,以实现用户身份验证。

首先,确保你已经在pubspec.yaml文件中添加了okta_oidc依赖:

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

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

配置Okta OIDC客户端

在你的Flutter项目中,创建一个配置类来存储Okta OIDC客户端的设置。例如,创建一个名为okta_config.dart的文件:

import 'package:okta_oidc/okta_oidc.dart';

class OktaConfig {
  static final OktaOidcClientConfig oidcConfig = OktaOidcClientConfig(
    issuer: "https://{yourOktaDomain}/oauth2/default",
    clientId: "{yourClientId}",
    redirectUri: "{yourRedirectUri}", // 例如: com.example.app:/callback
    scopes: ["openid", "profile", "email"],
  );
}

确保将{yourOktaDomain}, {yourClientId}, 和 {yourRedirectUri}替换为你的Okta域、客户端ID和重定向URI。

初始化Okta OIDC客户端

在你的应用的主文件中(例如main.dart),初始化Okta OIDC客户端并处理身份验证流程:

import 'package:flutter/material.dart';
import 'package:okta_oidc/okta_oidc.dart';
import 'okta_config.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Okta OIDC Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late OktaOidcClient _oktaOidcClient;

  @override
  void initState() {
    super.initState();
    _oktaOidcClient = OktaOidcClient(config: OktaConfig.oidcConfig);

    // 监听身份验证状态变化
    _oktaOidcClient.onAuthRequired = () async {
      try {
        await _oktaOidcClient.login();
      } catch (e) {
        print("Login error: $e");
      }
    };

    // 检查当前用户是否已登录
    _oktaOidcClient.checkAuthStatus().then((authStatus) {
      if (authStatus == OktaAuthStatus.isAuthenticated) {
        // 用户已登录,获取用户信息
        _oktaOidcClient.getUserInfo().then((userInfo) {
          print("User Info: $userInfo");
        });
      } else {
        // 用户未登录,触发登录流程
        _oktaOidcClient.onAuthRequired!();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Okta OIDC Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            try {
              await _oktaOidcClient.login();
            } catch (e) {
              print("Login error: $e");
            }
          },
          child: Text('Login'),
        ),
      ),
    );
  }
}

处理回调

在你的AndroidManifest.xmlInfo.plist文件中,确保你已经添加了用于处理OAuth回调的配置。

对于Android,在AndroidManifest.xml中添加:

<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="com.example.app" android:host="callback" />
</intent-filter>

对于iOS,在Info.plist中添加:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.example.app</string>
        </array>
    </dict>
</array>

并在你的AppDelegate.swiftAppDelegate.m中处理回调URL:

// AppDelegate.swift
import UIKit
import Flutter
import okta_oidc

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    OktaOidcPlugin.setApplication(application)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return OktaOidcPlugin.application(app, open: url, options: options)
  }
}
// AppDelegate.m
#import "AppDelegate.h"
#import <Flutter/Flutter.h>
#import <okta_oidc/OktaOidcPlugin.h>

@interface AppDelegate ()
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  [OktaOidcPlugin setApplication:application];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  return [OktaOidcPlugin application:app openURL:url options:options];
}

@end

这个示例展示了如何在Flutter应用中使用okta_oidc插件进行身份验证。你可以根据需要进一步自定义和扩展这个示例。

回到顶部