9

Có cách nào để kiểm tra xem người dùng có được ủy quyền Firebase trước khi kích hoạt chức năng đám mây không? (Hoặc trong hàm)Trình kích hoạt HTTP an toàn cho chức năng đám mây cho Firebase

+2

Có thể sao chép [Làm thế nào để bảo vệ Firebase Cloud Function Điểm cuối HTTP chỉ cho phép người dùng xác thực Firebase?] (Http://stackoverflow.com/questions/ 42751074/how-to-protect-firebase-cloud-chức năng-http-endpoint-to-allow-only-firebase-auth) –

Trả lời

30

Có. Bạn sẽ cần gửi mã thông báo ID Firebase cùng với yêu cầu (ví dụ: trong tiêu đề Authorization của yêu cầu AJAX), sau đó xác minh nó bằng SDK quản trị Firebase. Có một in-depth example trong vùng Cloud Functions cho kho lưu trữ mẫu Firebase. Nó trông giống như thế này (viết tắt là SO post):

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
const cors = require('cors')(); 

const validateFirebaseIdToken = (req, res, next) => { 
    cors(req, res,() => { 
    const idToken = req.headers.authorization.split('Bearer ')[1]; 
    admin.auth().verifyIdToken(idToken).then(decodedIdToken => { 
     console.log('ID Token correctly decoded', decodedIdToken); 
     req.user = decodedIdToken; 
     next(); 
    }).catch(error => { 
     console.error('Error while verifying Firebase ID token:', error); 
     res.status(403).send('Unauthorized'); 
    }); 
    }); 
}; 

exports.myFn = functions.https.onRequest((req, res) => { 
    validateFirebaseIdToken(req, res,() => { 
    // now you know they're authorized and `req.user` has info about them 
    }); 
}); 
Các vấn đề liên quan