Skip to content

karelklic/firebase_verify_token_dart

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Firebase Verify Token

A Flutter plugin that allows you to verify Firebase JWT Tokens across multiple Firebase projects.

Pub Version Pub Likes Pub Likes Pub Likes GitHub license

📱 Supported Platforms

Android iOS MacOS Web Linux Windows
✔️ ✔️ ✔️ ✔️ ✔️ ✔️

🔍 Overview

This plugin verifies Firebase JWT tokens through a series of checks:

  • Validates that the token was generated by one of your specified Firebase Project IDs
  • Confirms the token was issued by Firebase Authentication
  • Verifies the token has not expired

⚙️ Installation

Import the Firebase Verify Token package

To use the Firebase Verify Token package, follow the plugin installation instructions.

Basic Usage

Add the following import to your Dart code:

import 'package:firebase_verify_token/firebase_verify_token.dart';

🔐 Configuration

Before using the package, initialize it with your Firebase project IDs:

FirebaseVerifyToken.projectIds = ['project-id-1', 'project-id-2'];

🧩 Token Verification

Basic Verification

The simplest way to verify a token:

bool isValid = await FirebaseVerifyToken.verify('your-firebase-jwt-token');

if (isValid) {
  // Token is valid, proceed with your logic
} else {
  // Token is invalid or expired
}

With Callback

You can use a callback to get more detailed verification results:

await FirebaseVerifyToken.verify(
  'your-firebase-jwt-token',
  onVerifySuccessful: ({required bool status, String? projectId}) {
    if (status) {
      print('Token verified for project: $projectId');
      // Handle successful verification
    } else {
      print('Token verification failed');
      // Handle verification failure
    }
  },
);

📝 Verification Process

The verification process includes these checks:

  1. Token Format: Validates the token has the correct JWT structure
  2. Project ID: Confirms the token was issued by one of your configured Firebase projects
  3. Issuer Verification: Ensures the token was issued by Firebase Authentication
  4. Expiration Check: Verifies the token hasn't expired

🔄 Complete Usage Example

import 'package:flutter/material.dart';
import 'package:firebase_verify_token/firebase_verify_token.dart';

void main() {
  // Initialize the Firebase Verify Token with your project IDs
  FirebaseVerifyToken.projectIds = [
    'my-firebase-project-1',
    'my-firebase-project-2',
  ];
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final TextEditingController _tokenController = TextEditingController();
  String _verificationResult = '';

  Future<void> _verifyToken() async {
    final String token = _tokenController.text.trim();
    
    if (token.isEmpty) {
      setState(() {
        _verificationResult = 'Please enter a token';
      });
      return;
    }
    
    try {
      final bool isValid = await FirebaseVerifyToken.verify(
        token,
        onVerifySuccessful: ({required bool status, String? projectId}) {
          if (status) {
            setState(() {
              _verificationResult = 'Valid token for project: $projectId';
            });
          } else {
            setState(() {
              _verificationResult = 'Invalid token';
            });
          }
        },
      );
      
      if (!isValid) {
        setState(() {
          _verificationResult = 'Token verification failed';
        });
      }
    } catch (e) {
      setState(() {
        _verificationResult = 'Error: ${e.toString()}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Firebase Token Verification')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
              controller: _tokenController,
              decoration: InputDecoration(
                labelText: 'Firebase JWT Token',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _verifyToken,
              child: Text('Verify Token'),
            ),
            SizedBox(height: 24),
            Text(
              'Result:',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 8),
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(_verificationResult),
            ),
          ],
        ),
      ),
    );
  }
}

💡 Common Use Cases

  • Cross-project authentication: Verify tokens issued by different Firebase projects
  • API authentication: Use Firebase tokens for securing backend API requests
  • Multi-app ecosystems: Allow users from different Firebase apps to access shared resources

🤝 Contributing

Contributions are welcome! Open an issue or submit a pull request.

📃 License

This package is released under the MIT license. See the LICENSE file for more details.

About

Package to verify a firebase jwt token by a specific project id

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Dart 100.0%