搜索插件、代码仓与 APP 分类

插件详情v3.2.0

local_session_timeout

如果应用程序在 'x' 持续时间内未收到任何用户操作或在后台运行,则重定向用户到认证页面。

AndroidiOSWebmacOSWindowsLinux
近 30 天下载
1.6万
喜欢数
102
Pub 分数
150

安装插件

flutter pub add local_session_timeout

插件介绍

基于插件公开信息、社区数据与项目使用情况整理的选型参考。

local_session_timeout 包会在用户指定的不活动时间段后或应用在后台运行过久时,自动将用户重定向到身份验证页面。它通过基于用户交互或经过的时间强制会话超时来提高安全性。适用于需要安全访问控制的应用程序,可在 Android、iOS、Web、macOS、Windows 和 Linux 等多个平台上使用。该包可使用简单配置与 Flutter 应用无缝集成。

适合场景

  • 在移动应用中保护敏感数据
  • 在不活动后强制自动登出
  • 保护用户在网页和桌面端的会话
  • 防止在长时间后台使用期间未经授权的访问
  • 实现基于时间的会话过期

主要特点

  • 自动重定向在不活动时
  • 背景超时检测
  • 跨平台支持
  • 与 Flutter 的简单集成
  • 可配置的超时持续时间
  • 可自定义重定向路由

适合对象

  • 安全的Flutter应用程序
  • 处理个人或财务数据的应用程序
  • 企业级认证需求
  • 需要一致会话管理的多平台应用
  • 开发人员优先考虑用户安全

使用建议

  • 需要正确处理导航状态
  • 可能需要针对复杂路由进行定制
  • 依赖准确的系统时间和后台执行
  • 不适合需要持续活跃会话的实时应用程序
  • 应在不同平台上进行彻底测试

原始 README

以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。

  • With local_session_timeout you can redirect user to authentication page, if the application hasn't received any user interaction, or been running in the background for "x" duration.
  • Works locally, does not require internet connection.
  • Useful for apps with confidential information. If the user leaves the app running, or pushes it to the background to use later and forgets to close it.
  • Works on android, ios, web and desktop.

Getting started

import 'package:local_session_timeout/local_session_timeout.dart';
Create SessionConfig object

An object responsible for specifying durations for different types of timeouts.

It exposes a stream which can be listened for timeout events

final sessionConfig = SessionConfig(
    invalidateSessionForAppLostFocus: const Duration(seconds: 15),
    invalidateSessionForUserInactivity: const Duration(seconds: 30));

// If you don't have access to Navigator via context, you can access it like this
final navigatorKey = GlobalKey<NavigatorState>();
NavigatorState get _navigator => navigatorKey.currentState!;

sessionConfig.stream.listen((SessionTimeoutState timeoutEvent) {
    if (timeout == SessionTimeoutState.userInactivityTimeout) {
        // handle user  inactive timeout
        _navigator.pushNamed("/auth");
    } else if (imeout == SessionTimeoutState.appFocusTimeout) {
        // handle user  app lost focus timeout
        _navigator.pushNamed("/auth");
    }
});
Parameters
  • invalidateSessionForAppLostFocus (Duration? duration): appFocusTimeout event will be emitted through the stream, if the app loses focus and running in background for specified duration. If duration passed is null, app will not emit timeout events for losing focus / pushed into background.

  • invalidateSessionForUserInactivity (Duration? duration): userInactivityTimeout event will be emitted through the stream, if the app doesn't recieve any user activity for specified duration. If duration passed is null, app will not emit timeout events for user inactivity.

Create SessionTimeoutManager object
StreamController<SessionState> sessionStateStream:
SessionTimeoutManager(
    sessionConfig: sessionConfig,
    sessionStateStream: sessionStream,
    userActivityDebounceDuration: const Duration(seconds: 10),
    child: MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
        primarySwatch: Colors.blue,
    ),
    home: const MyHomePage(title: 'Flutter Demo Home Page'),
    )
);
Parameters
  • sessionConfig (SessionConfig sessionConfig): sessionConfig object that was created previously.

  • child (Widget widget): child widget in widget tree.

  • userActivityDebounceDuration (Duration duration) (optional): Since creating a timer object for each user interaction can be CPU intensive, a new timer will be started only in the intervals of userActivityDebounceDuration duration, has default value of 10 seconds.

  • sessionStateStream<SessionState> (StreamController<SessionState>) (optional):

    • If the argument is not passed, session timeout manager will always be listening.
    • If the argument is passed, developer can selectively disable the session timeout manager and re-enable it.
    Sometimes you may want to disable the session timeout manager and re-enable it, consider the following scenarios:
    • User might be in a page reading someting which doesn't contribute to any user inactivity, so you may want to disable the session timeout manager when user is in this page.
    • Typing (both soft keyboard and hardware keyboard) isn't recorded by session timeout manager as user activity, because it is not possible to listen to keyboard events from outside the TextField widget in Flutter, so you may want to disable listener when soft keyboard is open.
    • You may want to disable session timeout manager in auth page, as it doesn't makes much sense to redirect to auth page from auth page.
    • To disable session timeout manager, pass SessionState.stopListening to this stream, and to re-enable session timeout manager, pass SessionState.startListening to this stream. (Developer is responsible for handling and disposing of streamController passed). If you don't pass this argument, session timeout manager will always be listening.

    All of the above usecases are covered in example app

Note: Make sure to keep SessionTimeoutManager as top level widget of your widget tree, so that it records user activity in all screens

Sample Usage (refer example app for complete usage)

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final sessionConfig = SessionConfig(
        invalidateSessionForAppLostFocus: const Duration(seconds: 15),
        invalidateSessionForUserInactivity: const Duration(seconds: 30));

    sessionConfig.stream.listen((SessionTimeoutState timeoutEvent) {
    if (timeoutEvent == SessionTimeoutState.userInactivityTimeout) {
        // handle user  inactive timeout
        // Navigator.of(context).pushNamed("/auth");
    } else if (timeoutEvent == SessionTimeoutState.appFocusTimeout) {
        // handle user  app lost focus timeout
        // Navigator.of(context).pushNamed("/auth");
    }
});

    return SessionTimeoutManager(
      sessionConfig: sessionConfig,
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

Support

All OS's will support userInactivityTimeout, but appLostFocusTImeout is supported only on mobile devices (Android and IOS) as Flutter doesn't support widget lifecycle methods on desktop and Web.

Additional information

This package can be used for both online and offline applications. Even if the application has session / token based auth with webserver, invalidating the session may require require communication with web server, which is not possibe if the user turns off internet connection and pushes the app to the background.

所属分类

源码仓库

使用此插件的项目