simple_auth

大多数应用程序都需要进行 API 调用。每个 API 都需要身份验证,但没有开发者愿意处理身份验证。Simple Auth 将身份验证嵌入到 API 中,因此您无需处理它。

这是 Clancey.SimpleAuth for Dart and Flutter 的移植版。

网络/API 部分(包括生成器)基于 Hadrien Lejard 的 Chopper。

Providers

当前内置提供商

  • Azure Active Directory
  • 亚马逊
  • Dropbox
  • Facebook
  • Github
  • Google
  • Instagram
  • Linked In
  • Microsoft Live Connect
  • 当然还有任何标准的 OAuth2/Basic Auth 服务器。

用法

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

就是这样!如果用户未登录,系统将自动提示。如果用户凭证已从先前会话中缓存,API 调用将继续进行!令牌过期也会自动刷新。

Flutter 设置

在您的 Main.Dart 中调用 SimpleAuthFlutter.init();。现在 Simple Auth 可以自动显示您的登录 UI。

重定向

Google 要求以下重定向 URI:com.googleusercontent.apps.YOUR_CLIENT_ID

Simple Auth 默认在 iOS 上使用 SFSafari,在 Android 上使用 Chrome Tabs。

这意味着普通的 http 重定向无法工作。您需要为您的应用程序注册一个自定义方案作为重定向。对于大多数提供商,您可以创建任何您想要的。例如:com.myapp.foo:/redirct

Android Manifest

然后您需要在 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

在 iOS 上,您需要在 AppDelegate 中添加以下内容。

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

对于 iOS 11 及更高版本,您无需执行其他操作。在旧版 iOS 上,需要在 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>
	

序列化

如果您符合 JsonSerializable,JSON 对象将自动序列化。

如果您使用生成器,并且您的对象具有工厂方法 factory JsonSerializable.fromJson(Map<String, dynamic> json),那么您的 API 调用将自动进行序列化/反序列化。

或者,您可以将自己的 Converter 传递给 API,并自行处理转换。

生成器

Dart

pub run build_runner build

flutter

flutter packages pub run build_runner build

将以下内容添加到您的 pubspec.yaml 中:

dev_dependencies:
  simple_auth_generator: 
  build_runner: ^0.8.0

生成器不是必需的,但它会让一切变得神奇。

@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();
}

将为您生成一个新的易于使用的 API!

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

GitHub

https://github.com/Clancey/simple_auth