| FLUTTER FIREBASE AUTHENTICATION

Được viết bởi thanhdt vào ngày 28/11/2025 lúc 21:31 | 43 lượt xem

FLUTTER FIREBASE AUTHENTICATION

Email/Password – Google Sign-In – Apple Sign-In – Token – Secure Storage

https://firebase.google.com/static/docs/cloud-messaging/images/diagram-FCM.png
https://blog.flutterflow.io/content/images/size/w1200/2022/05/flutterflow-todo-1-cover-wide.png
https://www.researchgate.net/publication/373791023/figure/fig4/AS%3A11431281187508872%401694268090244/Authentication-Flowchart-shows-an-authentication-flowchart-where-to-be-able-to-login-to.ppm

Firebase Authentication là giải pháp đăng nhập phổ biến nhất cho ứng dụng Flutter năm 2025. Firebase cung cấp nhiều phương thức:

  • Email/Password
  • Google Sign-In
  • Apple Sign-In
  • Phone Authentication
  • Anonymous Login
  • Custom Token
  • Third-party OAuth

Bài này hướng dẫn quy trình đầy đủ từ cài đặt → cấu hình → code thực hiện → quản lý phiên đăng nhập.


1. KHỞI TẠO DỰ ÁN FIREBASE

https://codewithandrea.com/videos/starter-architecture-flutter-firebase/images/application-layers.png
https://www.quickcoder.org/wp-content/uploads/2023/07/project_overview_project_settings.png

Các bước:

  1. Vào console.firebase.google.com
  2. Tạo Project
  3. Thêm App Android
  4. Thêm App iOS
  5. Tải file:
    • google-services.json (Android)
    • GoogleService-Info.plist (iOS)
  6. Kích hoạt Authentication → Sign-in Method

Sau đó thêm dependencies:

firebase_core: ^3.0.0
firebase_auth: ^5.0.0
google_sign_in: ^7.0.0
flutter_secure_storage: ^9.0.0

Khởi tạo Firebase trong main.dart:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

2. EMAIL / PASSWORD AUTH

https://i.ytimg.com/vi/Dyu-tcX0H7M/hq720.jpg?rs=AOn4CLAwptFRZSZmiyPVkHOFBWJTv3-DTg&sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD
https://firebase.flutter.dev/assets/images/ui-auth-signin-header-79cb0b01a526d949757abee8940a3278.png

Đăng ký tài khoản

final credential = await FirebaseAuth.instance
    .createUserWithEmailAndPassword(
        email: email, password: password);

Đăng nhập

final credential = await FirebaseAuth.instance
    .signInWithEmailAndPassword(
        email: email, password: password);

Đăng xuất

await FirebaseAuth.instance.signOut();

3. GOOGLE SIGN-IN

https://i.ytimg.com/vi/2GdJnV-C5GI/maxresdefault.jpg
https://storage.googleapis.com/gweb-cloudblog-publish/images/firebase-aunthentication0s8a.max-700x700.PNG

Đăng nhập Google cần 2 thư viện:

  • firebase_auth
  • google_sign_in

Triển khai:

final googleUser = await GoogleSignIn().signIn();
final googleAuth = await googleUser?.authentication;

final credential = GoogleAuthProvider.credential(
  accessToken: googleAuth?.accessToken,
  idToken: googleAuth?.idToken,
);

await FirebaseAuth.instance.signInWithCredential(credential);

4. APPLE SIGN-IN (BẮT BUỘC CHO iOS)

https://docs.flutterflow.io/assets/images/opt-to-hide-email-9ce8755a705492a463894be5e304fef7.png
https://www.filledstacks.com/assets/tutorials/069/2.png.webp

Apple yêu cầu apps có Google/Facebook login phải hỗ trợ Sign in with Apple.

Thêm:

sign_in_with_apple: ^6.0.0

Code:

final credential = await SignInWithApple.getAppleIDCredential(
  scopes: [AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName],
);

final firebaseCredential = OAuthProvider("apple.com").credential(
  idToken: credential.identityToken,
  accessToken: credential.authorizationCode,
);

await FirebaseAuth.instance.signInWithCredential(firebaseCredential);

5. PHONE AUTHENTICATION

https://community.appinventor.mit.edu/uploads/default/original/3X/7/1/717033f0f1b3054c318fc10022c10094297c73f8.jpeg
https://user-images.githubusercontent.com/37796466/120930941-a7e75e80-c719-11eb-9d4a-845eeed8497b.png

Firebase sẽ gửi mã OTP SMS.

await FirebaseAuth.instance.verifyPhoneNumber(
  phoneNumber: phone,
  verificationCompleted: (credential) {
    FirebaseAuth.instance.signInWithCredential(credential);
  },
  verificationFailed: (_) {},
  codeSent: (id, _) {
    verifyId = id;
  },
  codeAutoRetrievalTimeout: (_) {},
);

Xác nhận OTP:

final credential = PhoneAuthProvider.credential(
  verificationId: verifyId,
  smsCode: otp,
);
await FirebaseAuth.instance.signInWithCredential(credential);

6. LƯU TOKEN VỚI SECURE STORAGE

FirebaseAuth cung cấp idTokenrefreshToken.
Người dùng có thể đăng nhập lại tự động.

final user = FirebaseAuth.instance.currentUser;
final token = await user?.getIdToken();

Lưu vào SecureStorage:

await storage.write(key: "token", value: token);

Đăng nhập lại:

final token = await storage.read(key: "token");
if (token != null) {
  // Auto login
}

7. STREAM AUTH STATE (KIỂM TRA NGƯỜI DÙNG ĐANG LOGIN)

https://i.ytimg.com/vi/VURoyY4LvXI/maxresdefault.jpg
https://codewithandrea.com/articles/simple-authentication-flow-with-flutter/images/simple-auth-flow-widget-tree.png

FirebaseAuth phát ra stream cập nhật mỗi khi trạng thái user thay đổi.

Sử dụng StreamBuilder:

StreamBuilder(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (context, snapshot) {
    if (snapshot.hasData) return Dashboard();
    return LoginScreen();
  },
);

8. TÍCH HỢP FIREBASE AUTH VỚI BACKEND RIÊNG

Nếu ứng dụng có backend (NodeJS, Python, Go…), bạn có thể xác minh token Firebase phía server.

Backend nhận token:

Authorization: Bearer <firebase_id_token>

Middleware xác minh:

  • NodeJS: firebase-admin
  • Flask/FASTAPI: firebase_admin
  • Go: firebase-auth

9. XỬ LÝ LỖI & THÔNG ĐIỆP CHUẨN

Các lỗi thường gặp:

  • invalid-email
  • wrong-password
  • user-not-found
  • account-exists-with-different-credential
  • network-request-failed

Ví dụ:

try {
  await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: email,
    password: password,
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'wrong-password') {
    message = "Password không đúng";
  }
}

10. KẾT HỢP AUTH + CRUD TRONG ỨNG DỤNG

Mô hình chuẩn:

https://www.researchgate.net/publication/363725063/figure/fig2/AS%3A11431281087055732%401664451728535/Flow-chart-of-operation-of-the-Firestore-database.ppm
https://media.licdn.com/dms/image/v2/D5612AQGiaFqMe_CTPQ/article-cover_image-shrink_600_2000/article-cover_image-shrink_600_2000/0/1721975377835?e=2147483647&t=c79RS5G_3p0vZlbpPshGq_dsVGxvZQt8_wzdahSVtWY&v=beta

Luồng:

  1. Đăng nhập → Lấy token Firebase
  2. Gửi token lên backend
  3. Backend xác thực
  4. Flutter gọi API CRUD
  5. UI cập nhật theo state

11. TỔNG KẾT

Firebase Authentication cung cấp giải pháp đăng nhập nhanh, bảo mật và đa nền tảng cho Flutter, bao gồm:

  • Email/Password
  • Google
  • Apple
  • OTP Phone
  • Custom Token
  • State stream realtime
  • Secure Storage

Ứng dụng thực tế có thể kết hợp Firebase Auth với Firestore hoặc backend riêng để hoàn thiện chức năng.


THAM CHIẾU – HỌC FLUTTER

Tài liệu và lộ trình Flutter đầy đủ:
https://www.huongnghieplaptrinhflutter.com/