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

패키지 상세v2.0.11

simple_auth_flutter

Simple Auth는 사용자 및 API 인증을 가장 간단하게 처리할 수 있는 방법입니다. 이 플러그인은 토큰/자격 증명을 안전하게 저장하며, 필요 시 자동으로 로그인 UI를 표시합니다.

AndroidiOSmacOS
30일 다운로드
108
좋아요
69
Pub 점수
115

패키지 설치

flutter pub add simple_auth_flutter

패키지 개요

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

Simple Auth Flutter는 Flutter 앱에서 사용자 인증을 간소화하는 가벼운 인증 패키지입니다. 토큰과 자격 증명을 안전하게 저장하고, 필요 시 자동으로 로그인 UI를 표시하며 다양한 신원 제공자와 원활하게 통합됩니다. 사용이 쉬우며 봇러플레이트 코드를 줄이고 보안 최선의 실천 방법을 유지합니다. Android, iOS, macOS를 지원하여 단순한 인증 워크플로우가 필요한 크로스플랫폼 애플리케이션에 이상적입니다.

사용 사례

  • 사용자 로그인 및 세션 관리
  • 자동 재인증
  • 보안 토큰 저장
  • OAuth 공급자와의 통합
  • 크로스 플랫폼 인증

주요 기능

  • 보안 자격 증명 저장
  • 자동 로그인 UI 프롬프트
  • 최소 설정
  • 여러 플랫폼을 지원합니다
  • 내장 토큰 지속성

적합한 대상

  • 초보자 플러터 개발자
  • 기본 인증이 필요한 앱
  • 긴 마감일이 있는 프로젝트
  • 크로스 플랫폼 모바일 앱
  • 간단한 로그인 흐름

고려 사항

  • 로그인 화면에 대한 사용자 정의 제한
  • 복잡한 인증 워크플로우에 적합하지 않습니다
  • 외부 공급자 구현에 의존함
  • 내장된 사용자 등록 없음
  • 토큰 갱신 로직을 신중하게 처리해야 합니다

원본 README

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

Simple Auth Pub Most apps need to make API calls. Every API needs authentication, yet no developer wants to deal with authentication. Simple Auth embeds authentication into the API so you dont need to deal with it.

This is a port of Clancey.SimpleAuth for Dart and Flutter

The network/api part including the generator was based off of Chopper by Hadrien Lejard

Join the chat at https://gitter.im/simple_auth/community

iOS: Build status

Android: Build status

Providers

Current Built in Providers
  • Azure Active Directory
  • Amazon
  • Dropbox
  • Facebook
  • Github
  • Google
  • Linked In
  • Microsoft Live Connect
  • Keycloak
  • And of course any standard OAuth2/Basic Auth server.

Usage

var api = new simpleAuth.GoogleApi(
      "google", "client_id",clientSecret: "clientSecret",
      scopes: [
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile"
      ]);
var request = new Request(HttpMethod.Get, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
var userInfo = await api.send<UserInfo, UserInfo>(request);

That's it! If the user is not logged in, they will automatically be prompted. If their credentials are cached from a previous session, the api call proceeds! Expired tokens even automatically refresh.

Flutter Setup

Call SimpleAuthFlutter.init(); in your Main.Dart. Now Simple Auth can automatically present your login UI

Redirect

Google requires the following redirect: com.googleusercontent.apps.YOUR_CLIENT_ID

Simple Auth by default uses SFSafari on iOS and Chrome Tabs on Android.

This means normal http redirects cannot work. You will need to register a custom scheme for your app as a redirect. For most providers, you can create whatever you want. i.e. com.myapp.foo:/redirct

Android Manifest

you would then add the following to your Android manifest

<activity android:name="clancey.simpleauth.simpleauthflutter.SimpleAuthCallbackActivity" >
    <intent-filter android:label="simple_auth">
        <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.myapp.foo" />
    </intent-filter>
</activity>

For instagram, the above won't work, as it will only accept redirect URIs that start with https. Add the following instead:

    <activity android:name="clancey.simpleauth.simpleauthflutter.SimpleAuthCallbackActivity">

      <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="http" />
        <data android:scheme="https" />
        <data android:host="myflutterapp.com" />
      </intent-filter>
    </activity>

iOS & macOS

on iOS you need something like the following as your AppDelegate.m file under the Runner folder

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import <Flutter/Flutter.h>
#import <simple_auth_flutter/SimpleAuthFlutterPlugin.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  // Override point for customization after application launch.
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

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

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    return [SimpleAuthFlutterPlugin checkUrl:url];
}

@end

On macOS:

import Cocoa
import FlutterMacOS
import simple_auth_flutter

@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
  override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    return true
  }
    
    override func applicationDidFinishLaunching(_ notification: Notification) {
        let appleEventManager:NSAppleEventManager = NSAppleEventManager.shared()
        appleEventManager.setEventHandler(self, andSelector: #selector(AppDelegate.handleGetURLEvent(event:replyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))

    }
    
    @objc func handleGetURLEvent(event: NSAppleEventDescriptor, replyEvent: NSAppleEventDescriptor) {
        let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue!
        let url = URL(string: urlString!)!
        SimpleAuthFlutterPlugin.check(url);
    }
}

For iOS 11/macOS 10.15 and higher, you don't need to do anything else. On older versions the following is required in the info.plist

	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>com.myapp.foo</string>
			</array>
			<key>CFBundleURLName</key>
			<string>myappredirect</string>
		</dict>
	</array>

Note, if you want to avoid Apples mandatory user consent dialog

"foo" Wants to use "bar.com" to Sign In
This allows the app and website to share information about you.

add the lines above and set FooAuthenticator.useSSO = false; which will not use SFAuthenticationSession on iOS, and ASWebAuthenticationSession on macOS. This is the default behavior for the Keycloak provider.

Serialization

Json objects will automatically serialize if you conform to JsonSerializable

If you use the generator and you objects have the factory factory JsonSerializable.fromJson(Map<String, dynamic> json) your api calls will automatically Serialize/Deserialize

Or you can pass your own Converter to the api and handle conversion yourself.

Generator

Dart
pub run build_runner build
flutter
flutter packages pub run build_runner build

Add the following to your pubspec.yaml

dev_dependencies:
  simple_auth_generator:
  build_runner: ^0.8.0

The Generator is not required, however it will make things magical.

@GoogleApiDeclaration("GoogleTestApi","client_id",clientSecret: "client_secret", scopes: ["TestScope", "Scope2"])
abstract class GoogleTestDefinition {
  @Get(url: "https://www.googleapis.com/oauth2/v1/userinfo?alt=json")
  Future<Response<GoogleUser>> getCurrentUserInfo();
}

will generate a new Api for you that is easy to use!

var api = new GoogleTestApi("google");
var user = await api.getCurrentUserInfo();

For more examples, check out the example project

Contributor

TODO

  • Add more documentation
  • Add native flutter providers for google

카테고리

의존성

의존성 목록 1 개

소스 저장소

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

아직 데이터가 없습니다.