Simple Auth 是一个轻量级的 Flutter 包,旨在简化应用程序和 API 的用户认证。它提供了一个简单且一致的接口,用于处理登录流程、令牌管理和跨多个平台的会话持久化。该包注重易于集成,支持 OAuth2、JWT 和自定义登录工作流等常见认证方法。该包抽象了复杂的实现细节,非常适合希望在无需样板代码的情况下获得最小但有效的认证解决方案的开发者。
适合场景
用户使用 OAuth2 登录
API令牌管理
会话持久性
自定义身份验证流程
跨平台认证
快速原型设计
主要特点
最小设置
支持多种认证类型
跨平台兼容性
令牌存储工具
干净的 API 设计
内置会话处理
适合对象
初学者Flutter开发者
需要基本身份验证的应用程序
快速应用开发
多平台项目
注重简洁的团队
使用建议
有限的高级功能
不适合企业级身份验证
无内置 UI 组件
依赖外部身份验证提供方
对底层逻辑的控制较少
仅适用于简单用例
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
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.
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 = newRequest(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
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.