simple_auth_flutter 1.0.6

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 92

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

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
  • 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

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

Android Manifest

Android requires you to add the callback scheme:

<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.googleusercontent.apps.992461286651-k3tsbcreniknqptanrugsetiimt0lkvo" />
    </intent-filter>
</activity>

iOS

To use the Native Safari Authenticator, you are required to add the following snippet in your AppDelegate.

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

You are also required to add the following to add a CFBundleURLSchemes to your info.plist

For Google: com.googleusercontent.apps.YOUR_CLIENT_ID

	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>com.googleusercontent.apps.YOURCLIENTID</string>
			</array>
			<key>CFBundleURLName</key>
			<string>googleLogin</string>
		</dict>
	</array>
	

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

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 getCurrentUserInfo();

For more examples, check out the example project

Contributor

TODO

  • Add more documentation
  • Add native flutter providers for google

[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/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 StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  initState() {
    super.initState();
    SimpleAuthFlutter.init(context);
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'SimpleAuth Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'SimpleAuth 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> {
  static String azureClientId = "";
  static String azureTennant = "";
  final simpleAuth.AzureADApi azureApi = new simpleAuth.AzureADApi(
      "azure",
      azureClientId,
      "https://login.microsoftonline.com/$azureTennant/oauth2/authorize",
      "https://login.microsoftonline.com/$azureTennant/oauth2/token",
      "https://management.azure.com/");

  final simpleAuth.BasicAuthApi basicApi = new simpleAuth.BasicAuthApi(
      "github-basic", "https://api.github.com/user");

  @override
  Widget build(BuildContext context) {
    SimpleAuthFlutter.context = 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: ListView(
        children: <Widget>[
          ListTile(
            title: Text(
              "AzureAD OAuth",
              style: Theme.of(context).textTheme.headline,
            ),
          ),
          ListTile(
            leading: Icon(Icons.launch),
            title: Text('Login'),
            onTap: () {
              login(azureApi);
            },
          ),
          ListTile(
            leading: Icon(Icons.delete),
            title: Text('Logout'),
            onTap: () {
              logout(azureApi);
            },
          ),
          ListTile(
            title: Text(
              "Github BasicAuth",
              style: Theme.of(context).textTheme.headline,
            ),
          ),
          ListTile(
            leading: Icon(Icons.launch),
            title: Text('Login'),
            onTap: () async {
              try {
                var success = await basicApi.authenticate();
                showMessage("Logged in success: $success");
              } catch (e) {
                showError(e);
              }
            },
          ),
          ListTile(
            leading: Icon(Icons.delete),
            title: Text('Logout'),
            onTap: () async {
              await basicApi.logOut();
              showMessage("Logged out");
            },
          ),
        ],
      ),
    );
  }

  void showError(dynamic ex) {
    showMessage(ex.toString());
  }

  void showMessage(String text) {
    var alert = new AlertDialog(content: new Text(text), actions: <Widget>[
      new FlatButton(
          child: const Text("Ok"),
          onPressed: () {
            Navigator.pop(context);
          })
    ]);
    showDialog(context: context, builder: (BuildContext context) => alert);
  }

  void login(simpleAuth.AuthenticatedApi api) async {
    try {
      var success = await api.authenticate();
      showMessage("Logged in success: $success");
    } catch (e) {
      showError(e);
    }
  }

  void logout(simpleAuth.AuthenticatedApi api) async {
    await api.logOut();
    showMessage("Logged out");
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  simple_auth_flutter: ^1.0.6

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages 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';
  
Version Uploaded Documentation Archive
1.0.6 Sep 5, 2018 Go to the documentation of simple_auth_flutter 1.0.6 Download simple_auth_flutter 1.0.6 archive
1.0.5 Sep 4, 2018 Go to the documentation of simple_auth_flutter 1.0.5 Download simple_auth_flutter 1.0.5 archive
1.0.4 Sep 4, 2018 Go to the documentation of simple_auth_flutter 1.0.4 Download simple_auth_flutter 1.0.4 archive
1.0.3 Aug 30, 2018 Go to the documentation of simple_auth_flutter 1.0.3 Download simple_auth_flutter 1.0.3 archive
1.0.2 Aug 30, 2018 Go to the documentation of simple_auth_flutter 1.0.2 Download simple_auth_flutter 1.0.2 archive
1.0.1 Jul 30, 2018 Go to the documentation of simple_auth_flutter 1.0.1 Download simple_auth_flutter 1.0.1 archive
1.0.0 Jul 30, 2018 Go to the documentation of simple_auth_flutter 1.0.0 Download simple_auth_flutter 1.0.0 archive
0.0.1 Jul 5, 2018 Go to the documentation of simple_auth_flutter 0.0.1 Download simple_auth_flutter 0.0.1 archive
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 Sep 18, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.3
  • Flutter: 0.8.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev <3.0.0
flutter 0.0.0
simple_auth ^1.0.6 1.0.6
Transitive dependencies
async 2.0.8
charcode 1.1.2
collection 1.14.11
http 0.11.3+17
http_parser 3.1.3
meta 1.1.6
path 1.6.2
sky_engine 0.0.99
source_span 1.4.1
string_scanner 1.0.4
typed_data 1.1.6
vector_math 2.0.8