• Stars
    star
    352
  • Rank 120,622 (Top 3 %)
  • Language
    Dart
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The Simplest way to Authenticate in Flutter

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

More Repositories

1

gMusic

This is a multi platform music player.
C#
203
star
2

SimpleAuth

The Simplest way to Authenticate and make Rest API calls in .Net
C#
171
star
3

FlyoutNavigation

C#
96
star
4

FlappyMonkey

C#
75
star
5

FlutterSharp

Dart
72
star
6

UICalendar

MonoTouch UICallendar control It contains day,month, and week view
C#
52
star
7

MonoMac.Windows.Form

Windows to Cocoa wrapper
C#
50
star
8

gMusic.Forms

C#
45
star
9

ClanceyLib

My Monotouch Library
C#
40
star
10

WormHoleSharp

C#
33
star
11

vscode-comet

C#
32
star
12

Reloadify3000

C#
23
star
13

XamlForIphone

Xaml for the iphone
C#
14
star
14

iOSHelpers

A collection of helpers to make the iOS api more sane/ .net like
C#
14
star
15

SimpleDatabase

Extension of Sqlite-net to make Databases simple for Mobile
C#
11
star
16

SimpleIoCApp

C#
10
star
17

appcenter_flutter_sample

Example building a Flutter app with AppCenter
Dart
10
star
18

Rosie

My Home Automation Project
C#
9
star
19

MonkeyBox

C#
9
star
20

BotFramework

C#
7
star
21

Canvas

C#
6
star
22

ToddlerAddition

A simple addition game created for Toddlers
C#
6
star
23

Bitly-sharp

Bit.ly rest api
C#
5
star
24

Common.Forms

Cross Platform dll for use with MonoMac.Windows.Froms
C#
5
star
25

SimpleSample

C#
5
star
26

Castles

C#
4
star
27

BMX_MonoGame

Monogame bmx game
C#
4
star
28

Wp7Sqlite

C#
3
star
29

gMusic-1

C#
3
star
30

SimpleCharts

C#
3
star
31

AppleMusicApi

C#
3
star
32

HtmlAgilityPack

HtmlAgilityPack Xamarin iOS compatible
C#
3
star
33

Memory

iPhone Memory Game
C#
3
star
34

SimpleTables

C#
3
star
35

FlashCards

C#
3
star
36

StreamHelper

My Twitch Maker Utility, that Tweets when the markers are added.
C#
3
star
37

TravelPlanner

C#
2
star
38

AmazonCloudDriveApi

C#
2
star
39

AdobeEdgeAnimations

Quickly turn Adobe edge websites into native apps
C#
2
star
40

SimpleSwaggerGenerator

C#
2
star
41

TeslaRemote

C#
2
star
42

MobileCenterApp

C#
1
star
43

SettingsBundle

C#
1
star
44

SwaggerSharp

C#
1
star
45

LocalPlex

C#
1
star
46

MonoTouchLastFmScrobbler

Monotouch port of http://lpfm.codeplex.com/
1
star
47

WcfTestSuite

C#
1
star
48

DuckHuntVR

C#
1
star
49

PaypalHere

Objective-C
1
star
50

lastfm-sharp

C#
1
star
51

OpenTK_gltut

C#
1
star
52

SlidingPanelSample

C#
1
star
53

ChannelGuide

C#
1
star
54

WebSocketWrapper

C#
1
star
55

Facetroids

C#
1
star
56

CometWeather

C#
1
star
57

DataSaver

C#
1
star
58

LocalHost

CSS
1
star