패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.5.1

keycloak_wrapper

Flutter 프레임워크용 Keycloak 단일 로그인(Single Sign-On, SSO) 인증 패키지.

AndroidiOSmacOS
30일 다운로드
1.8천
좋아요
34
Pub 점수
150

패키지 설치

flutter pub add keycloak_wrapper

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Keycloak 단일 로그인(SSO) 인증 통합을 간소화하는 플러터 패키지입니다. 안드로이드, iOS, macOS 플랫폼에서 로그인, 로그아웃, 토큰 관리 및 사용자 세션 상태를 처리하기 위한 간편한 인터페이스를 제공합니다. Keycloak의 인가 서버와 원활하게 작동하도록 설계되어 플러터 애플리케이션에서 안전하고 중앙 집중식 인증을 가능하게 합니다. 복잡한 OAuth2 흐름을 추상화하여 SSO 구현을 더 빠르고 신뢰할 수 있게 만듭니다.

사용 사례

  • 모바일 앱에 SSO 통합하기
  • Keycloak를 사용하여 사용자 세션 관리하기
  • OAuth2를 통한 앱 액세스 보안
  • 서비스 간 단일 로그인 활성화
  • 토큰 갱신 및 검증 처리

주요 기능

  • 내장된 OAuth2 흐름 지원
  • 크로스 플랫폼 호환성
  • 토큰 저장 및 검색
  • 세션 상태 관리
  • Keycloak 서버와의 간편한 통합

적합한 대상

  • Keycloak를 사용하는 모바일 앱
  • SSO 솔루션을 찾는 개발자
  • 보안 인증이 필요한 프로젝트
  • Keycloak를 신원 공급자로 사용하는 팀
  • 다중 플랫폼을 대상으로 한 Flutter 앱

고려 사항

  • 구성된 Keycloak 서버가 필요합니다
  • 올바른 리디렉션 URI 설정이 필요합니다
  • 사용자 지정 영역에 대해 추가 구성이 필요할 수 있습니다
  • OAuth2 기반 Keycloak 흐름에 한정
  • 인증 작업은 네트워크 연결에 따라 달라집니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Keycloak Wrapper

pub package likes pub points downloads style: lint StandWithPalestine


cover image

Integrate Keycloak Single Sign-On (SSO) authentication into your Flutter apps seamlessly using this package. Tokens are automatically managed under the hood and are easily accessible. A user authentication state stream is provided for your app to listen to in order to stay in sync with authentication status changes.

Getting Started

For end-user authentication and authorization, this package integrates with the AppAuth SDK to establish connections using OAuth 2.0 and OpenID Connect (OIDC). This integration allows users to securely log in and access protected resources, such as APIs or user data from third-party providers. For token security, the flutter_secure_storage package is used to securely store all tokens in the Keychain for iOS and Keystore for Android.

[!NOTE]

  • AndroidX is required for this package. Starting from Flutter v1.12.13, newly created projects enable AndroidX by default. If your project was created before this Flutter version, please migrate it before using this package. You can follow this migration guide provided by the Flutter team.

  • Starting with Android API 28 and iOS 9, insecure HTTP connections are disabled by default. Check out this guide if you want to allow cleartext connections for your build. However, it is not recommended for release builds. Please use secure connections whenever possible.

Keycloak

Go to your Keycloak Administration Console and select your Client ID. In the access settings section, add <bundle_identifier>:/* as a valid redirect URI, and do the same for the valid post logout redirect URI. Ensure your bundle identifier does not contain any characters that are not allowed in a hostname, such as spaces or underscores.

Android

Specify the custom scheme in your Android app’s build.gradle file. There should be a section similar to the following; replace <package_name> with your desired value:

android {
    ...
    defaultConfig {
        ...
        manifestPlaceholders += [
                'appAuthRedirectScheme': '<package_name>'
        ]
    }
}

Ensure that <package_name> is all lowercase, as there have been reports of issues with redirects if there are any capital letters. Note that the += operation is used on manifestPlaceholders instead of =. This is intentional and required, as newer versions of the Flutter SDK have made changes under the hood to handle multidex. Using = instead of += can lead to errors like the following:

Attribute application@name at AndroidManifest.xml:5:9-42 requires a placeholder substitution but no value for <applicationName> is provided.

If you see this error, update your build.gradle to use += instead.

[!WARNING]

  • Starting from Flutter v3.22.0, newly created projects will disallow task affinity by default to prevent the StrandHogg attack. However, these changes have broken the package, as users will no longer be able to redirect back to the app after login. Currently, the only way to fix this issue is to remove android:taskAffinity="" from your AndroidManifest.xml file.
iOS/macOS

Specify the custom scheme in your iOS/macOS app’s Info.plist file. There should be a section similar to the following; replace <bundle_identifier> with your desired value:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string><bundle_identifier></string>
        </array>
    </dict>
</array>

Usage

First, create an instance of the plugin somewhere in your code.

final keycloakWrapper = KeycloakWrapper();

Next, initialize the plugin with your own configuration values within the main() method to set up the user authentication stream as soon as your app launches.

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  keycloakWrapper.initialize(
    config: KeycloakConfig(
      bundleIdentifier: '<bundle_identifier>',
      clientId: '<client_id>',
      frontendUrl: '<frontend_url>',
      realm: '<realm>',
    ),
  );
  ...
  runApp(const MyApp());
}

To listen to the user authentication state stream, create a StreamBuilder widget that listens to keycloakWrapper.authenticationStream. Navigate the user to the login screen when the stream returns false, and redirect to the home screen when login is successful. Set the initial value of the StreamBuilder to false to ensure the stream never returns null.

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

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: StreamBuilder<bool>(
            initialData: false,
            stream: keycloakWrapper.authenticationStream,
            builder: (context, snapshot) =>
                snapshot.data! ? const HomeScreen() : const LoginScreen()),
      );
}

Then create a button somewhere in your login screen and use the following method to initiate the login process:

Future<void> login() async {
  final isLoggedIn = await keycloakWrapper.login();
}

Once logged in, you can retrieve the user's information and tokens as shown below:

// Retrieve user's information.
final user = await keycloakWrapper.getUserInfo();

final name = user?['name'];
final email = user?['email'];

// Retrieve tokens.
final accessToken = keycloakWrapper.accessToken;
final idToken = keycloakWrapper.idToken;
final refreshToken = keycloakWrapper.refreshToken;

To log out, simply call the following method. Make sure to pop all stacked screens, if there are any.

Future<void> logout() async {
  final isLoggedOut = await keycloakWrapper.logout();
}

By default, all errors and exceptions are handled by the onError method of the KeycloakWrapper class, which prints the error directly to the console. You can customize this behavior if you want to display a custom message to users when specific errors, such as authorization failures, occur. Below is an example of how you can override the method and handle errors and exceptions in your own way:

keycloakWrapper.onError = (message, error, stackTrace) {
  // Add your custom error handling logic here.
};

For further customization, you can customize the optional parameters available inside the configuration. All shown above are only the mandatory ones. You can refer to the example to see how this package works in a real-life app.

Contribute

Contributions are welcome! However, please make sure to follow the guidelines below to avoid unnecessary waste of time and resources.

  • Found a bug?
    Ensure the bug has not already been reported by searching on GitHub under Issues. If you can't find an open issue addressing the problem, open a new one. Be sure to include a title, a clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.

  • Need some help?
    Feel free to open a new discussion on GitHub if you need help from the community. I'll try my best to help you as soon as possible. If you want to make any feature requests, you can use the same platform for us to discuss your idea further.

  • Want to contribute?
    Since I am the only maintainer of this package, frequent bug fixes or updates might not be feasible. Therefore, any pull requests are greatly appreciated! Please ensure that the PR description clearly outlines both the problem and the proposed solution. If applicable, include the relevant issue number in the description.

Thanks! ❤️

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.