I am trying to implement App Check in my Xcode project, so that only my app is allowed to access the Firebase Database.
I've configured the App Check settings in Firebase. I've changed the Firebase Database rules to:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.token.app_check != null;
}
}
}
(The app doesn't require authentication) So that only if a valid token is received, it will grant access. My Swift code looks like this:
//
// Gossip_GirlApp.swift
// Gossip-Girl
//
// Created by Julius Pleunes on 25/11/2024.
//
import SwiftUI
import Firebase
import FirebaseAppCheck
@main
struct Gossip_GirlApp: App {
init() {
FirebaseApp.configure()
// Configureer App Check met DeviceCheck
AppCheck.setAppCheckProviderFactory(DeviceCheckProviderFactory())
// Debugging: Controleer Firebase configuratie
FirebaseConfiguration.shared.setLoggerLevel(.debug)
print("✅ Firebase en App Check zijn geconfigureerd")
// Debugging: Test App Check token
AppCheck.appCheck().token(forcingRefresh: true) { token, error in
if let error = error {
print("⚠️ Error fetching App Check token: \(error.localizedDescription)")
} else if let token = token?.token {
print("✅ App Check token: \(token)")
} else {
print("⚠️ App Check token is nil")
}
}
// Test Firestore-toegang
let db = Firestore.firestore()
db.collection("posts").getDocuments { snapshot, error in
if let error = error {
print("⚠️ Error fetching posts: \(error.localizedDescription)")
} else if let documents = snapshot?.documents {
print("✅ Successfully fetched posts:")
for document in documents {
print("\(document.documentID): \(document.data())")
}
} else {
print("⚠️ No documents found in 'posts' collection.")
}
}
}
var body: some Scene {
WindowGroup {
MainView() // Start met de tab bar view
}
}
}
As you can see, I am using the DeviceCheck feature to generate the key, but my app is failing to retrieve the data. If I change the Rules in Firebase to open to everyone, than it succesfully retrieves the data, so I think the problem lies in the Firebase code, but I cant figure out what is wrong
When trying to fetch the data, I see this error in the Xcode console:
⚠️ Error fetching posts: Missing or insufficient permissions.