simple_auth_flutter 2.0.7

  • Readme
  • Changelog
  • Example
  • Installing
  • 92

Simple Auth Pub

[![Join the chat at https://gitter.im/simple_auth/community](https://badges.gitter.im/simple_auth/community.svg)](https://gitter.im/simple_auth/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

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 Flutter adapter for the port of Clancey.SimpleAuth to Dart, (simple_auth)[https://github.com/Clancey/simple_auth]

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

iOS: Build status

Android: Build status

Providers #

Current Built in Providers #

  • Azure Active Directory
  • Amazon
  • Dropbox
  • Facebook
  • Github
  • Google
  • Instagram
  • 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>(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 #

Import package:simple_auth/simple_auth.dart and package:simple_auth_flutter/simple_auth_flutter.dart 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>

iOS #

on iOS you need the following in your app delegate.

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

For iOS 11 and higher, you don't need to do anything else. On older iOS 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. 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

[2.0.3] - 02-28-2019 #

  • Now works with Android X

[2.0.1] - 01-28-2019 #

  • Android now uses To Lower when comparing schemas
  • iOS 9 now works

[2.0] - 11-09-2018 #

  • The rest of the providers now require a redirect
  • Cleaned up dependencies

[1.0.7] - 09-26-2018 #

  • Fixed Canceling with Embedded Browser on iOS
  • Now works properly with Swift Flutter apps

[1.0.6] - 09-04-2018 #

  • Removed remaining redirect. Code Formatting.

[1.0.4] - 09-04-2018 #

  • Breaking Change: Redirects are now required. This prevents user error.
  • Fixed crash in Google Auth.

[1.0.3] - 08-30-2018 #

  • Updated dependencies

[1.0.2] - 08-30-2018 #

  • Updated dependencies

[1.0.1] - 07-30-2018 #

  • OAuth Bug fix

[0.0.1] - 07-05-2018 #

  • Initial release of Simple Auth

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:simple_auth/simple_auth.dart' as simpleAuth;
import 'package:simple_auth_flutter/simple_auth_flutter.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    SimpleAuthFlutter.init(context);
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  final simpleAuth.GoogleApi googleApi = new simpleAuth.GoogleApi("google",
      "992461286651-k3tsbcreniknqptanrugsetiimt0lkvo.apps.googleusercontent.com",
      "redirecturl",
      clientSecret: "avrYAIxweNZwcHpsBlIzTp04",
      scopes: [
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile"
      ]);

  void _incrementCounter() async {
    var profile = await googleApi.getUserProfile();
    print(profile.name);
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text(widget.title),
      ),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new Column(
          // Column is also layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug paint" (press "p" in the console where you ran
          // "flutter run", or select "Toggle Debug Paint" from the Flutter tool
          // window in IntelliJ) to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  simple_auth_flutter: ^2.0.7

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:simple_auth_flutter/simple_auth_flutter.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
84
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
92
Learn more about scoring.

We analyzed this package on Jul 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.13
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform linux

Because of import path [package:simple_auth_flutter/simple_auth_flutter.dart] that declares support for platforms: android, ios

Package does not support Flutter platform macos

Because of import path [package:simple_auth_flutter/simple_auth_flutter.dart] that declares support for platforms: android, ios

Package does not support Flutter platform web

Because of import path [package:simple_auth_flutter/simple_auth_flutter.dart] that declares support for platforms: android, ios

Package does not support Flutter platform windows

Because of import path [package:simple_auth_flutter/simple_auth_flutter.dart] that declares support for platforms: android, ios

Package not compatible with SDK dart

because of import path [simple_auth_flutter] that is in a package requiring null.

Health issues and suggestions

Document public APIs. (-0.12 points)

32 out of 33 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
flutter 0.0.0
simple_auth ^2.0.7 2.0.7
Transitive dependencies
charcode 1.1.3
collection 1.14.12 1.14.13
convert 2.1.1
crypto 2.1.5
http 0.12.1
http_parser 3.1.4
meta 1.1.8 1.2.1
path 1.7.0
pedantic 1.9.0 1.9.1
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8