使用新的firebase云功能,我决定将我的一些HTTP端点移动到firebase。 一切都很好......但我有以下问题。我有两个端点由HTTP触发器(云功能)构建
虽然第一个端点很好,但对于我的第二个端点,我想要仅为经过身份验证的用户保护它。意思是拥有我之前生成的令牌的人。
我如何解决这个问题?
我知道我们可以使用
获取云功能中的Header参数request.get('x-myheader')
但有没有办法保护端点就像保护实时数据库一样?
答案 0 :(得分:79)
有一位官方code sample代表您正在尝试做的事情。它说明了如何设置HTTPS功能以要求Authorization标头包含客户端在身份验证期间收到的令牌。该函数使用firebase-admin库来验证令牌。
此外,您可以使用" callable functions"如果您的应用能够使用Firebase客户端库,那么可以更轻松地使用这个样板。
答案 1 :(得分:67)
如@Doug所述,您可以使用firebase-admin
来验证令牌。我已经设置了一个简单的例子:
exports.auth = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const tokenId = req.get('Authorization').split('Bearer ')[1];
return admin.auth().verifyIdToken(tokenId)
.then((decoded) => res.status(200).send(decoded))
.catch((err) => res.status(401).send(err));
});
});
在上面的示例中,我还启用了CORS,但这是可选的。首先,您获得Authorization
标题并找到token
。
然后,您可以使用firebase-admin
来验证该令牌。您将在响应中获取该用户的已解码信息。否则,如果令牌无效,则会抛出错误。
我希望它有所帮助。
答案 2 :(得分:4)
以上方法使用逻辑 inside 函数对用户进行身份验证,因此必须仍然调用该函数以进行检查。
这是一种非常好的方法,但是为了全面理解,有一种替代方法:
您可以将一个功能设置为“私有”,以便除注册用户(您决定权限)外,不能调用 。在这种情况下,未经身份验证的请求将在函数上下文之外被拒绝,并且根本不会调用该函数。
以下是(a)Configuring functions as public/private,然后是(b)authenticating end-users to your functions的引用。
请注意,以上文档适用于Google Cloud Platform,并且确实如此,因为每个Firebase项目也是 一个GCP项目。与该方法相关的警告是,截至撰写时,它仅适用于基于Google帐户的身份验证。
答案 3 :(得分:0)
@Doug也提到过, 您可以使用Callable Functions来从客户端和服务器访问exclude some boilerplate code。
Exampale可调用函数:
export const getData = functions.https.onCall((data, context) => {
// verify Firebase Auth ID token
if (!context.auth) {
return { message: 'Authentication Required!', code: 401 };
}
// do your things..
const uid = context.auth.uid;
const query = data.query;
return { message: 'Some Data', code: 400 };
});
它可以像这样直接从您的客户端调用:
firebase.functions().httpsCallable('getData')({query}).then(result => console.log(result));
答案 4 :(得分:0)
有一个使用Express的不错的官方示例-将来可能会很方便:https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js(肯定会粘贴在下面)
请记住,exports.app
使您的功能在/app
子弹下可用(在这种情况下,只有一个功能并且在<you-firebase-app>/app/hello
下可用。要摆脱它,您实际上需要重写Express的一部分(用于验证的中间件部分保持不变-很好用,并且由于注释而可以理解)。
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const express = require('express');
const cookieParser = require('cookie-parser')();
const cors = require('cors')({origin: true});
const app = express();
// Express middleware that validates Firebase ID Tokens passed in the Authorization HTTP header.
// The Firebase ID token needs to be passed as a Bearer token in the Authorization HTTP header like this:
// `Authorization: Bearer <Firebase ID Token>`.
// when decoded successfully, the ID Token content will be added as `req.user`.
const validateFirebaseIdToken = async (req, res, next) => {
console.log('Check if request is authorized with Firebase ID token');
if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
!(req.cookies && req.cookies.__session)) {
console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
'Make sure you authorize your request by providing the following HTTP header:',
'Authorization: Bearer <Firebase ID Token>',
'or by passing a "__session" cookie.');
res.status(403).send('Unauthorized');
return;
}
let idToken;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
console.log('Found "Authorization" header');
// Read the ID Token from the Authorization header.
idToken = req.headers.authorization.split('Bearer ')[1];
} else if(req.cookies) {
console.log('Found "__session" cookie');
// Read the ID Token from cookie.
idToken = req.cookies.__session;
} else {
// No cookie
res.status(403).send('Unauthorized');
return;
}
try {
const decodedIdToken = await admin.auth().verifyIdToken(idToken);
console.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
next();
return;
} catch (error) {
console.error('Error while verifying Firebase ID token:', error);
res.status(403).send('Unauthorized');
return;
}
};
app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);
app.get('/hello', (req, res) => {
res.send(`Hello ${req.user.name}`);
});
// This HTTPS endpoint can only be accessed by your Firebase Users.
// Requests need to be authorized by providing an `Authorization` HTTP header
// with value `Bearer <Firebase ID Token>`.
exports.app = functions.https.onRequest(app);
我的改写摆脱了/app
:
const hello = functions.https.onRequest((request, response) => {
res.send(`Hello ${req.user.name}`);
})
module.exports = {
hello
}
答案 5 :(得分:0)
我一直在努力在golang GCP功能中获得适当的Firebase身份验证。实际上,没有任何示例,因此我决定构建这个小型库:https://github.com/Jblew/go-firebase-auth-in-gcp-functions
现在,您可以轻松地使用firebase-auth(与gcp-authenticated-functions不同,并且不受Identity-aware-proxy的直接支持)对用户进行身份验证。
以下是使用该实用程序的示例:
import (
firebaseGcpAuth "github.com/Jblew/go-firebase-auth-in-gcp-functions"
auth "firebase.google.com/go/auth"
)
func SomeGCPHttpCloudFunction(w http.ResponseWriter, req *http.Request) error {
// You need to provide 1. Context, 2. request, 3. firebase auth client
var client *auth.Client
firebaseUser, err := firebaseGcpAuth.AuthenticateFirebaseUser(context.Background(), req, authClient)
if err != nil {
return err // Error if not authenticated or bearer token invalid
}
// Returned value: *auth.UserRecord
}
请记住要使用--allow-unauthenticated
标志部署您的功能(因为在功能执行过程中发生了Firebase身份验证)。
希望这对您有所帮助,对我有帮助。由于性能原因,我决定将golang用于云功能 —Jędrzej
答案 6 :(得分:0)
在Firebase中,为了简化代码和工作,这只是建筑设计的问题:
Express
。要仅限制同一站点或仅特定站点,请使用CORS
来控制此方面的安全性。这是有道理的,因为Express
由于其服务器端呈现内容而对于SEO很有用。context
参数来保存所有麻烦。这也是有道理的,因为例如使用AngularJS构建的单页应用程序-AngularJS对SEO不利,但是由于它是受密码保护的应用程序,因此您也不需要太多SEO。至于模板,AngularJS具有内置模板,因此不需要带有Express
的服务器端模板。那么Firebase可调用函数应该足够好。牢记以上几点,不再麻烦,让生活更轻松。
答案 7 :(得分:0)
您可以将此作为函数返回布尔值。如果用户已验证,那么您将继续或停止您的API。此外,您还可以从解码变量中返回声明或用户结果
const authenticateIdToken = async (
req: functions.https.Request,
res: functions.Response<any>
) => {
try {
const authorization = req.get('Authorization');
if (!authorization) {
res.status(400).send('Not Authorized User');
return false;
}
const tokenId = authorization.split('Bearer ')[1];
return await auth().verifyIdToken(tokenId)
.then((decoded) => {
return true;
})
.catch((err) => {
res.status(401).send('Not Authorized User')
return false;
});
} catch (e) {
res.status(400).send('Not Authorized User')
return false;
}
}
答案 8 :(得分:0)
这里有很多很好的信息对我很有帮助,但我认为对于第一次尝试使用 Angular 的人来说,分解一个简单的工作示例可能会很好。可以在 https://firebase.google.com/docs/auth/admin/verify-id-tokens#web 中找到 Google Firebase 文档。
//#### YOUR TS COMPONENT FILE #####
import { Component, OnInit} from '@angular/core';
import * as firebase from 'firebase/app';
import { YourService } from '../services/yourservice.service';
@Component({
selector: 'app-example',
templateUrl: './app-example.html',
styleUrls: ['./app-example.scss']
})
export class AuthTokenExample implements OnInit {
//property
idToken: string;
//Add your service
constructor(private service: YourService) {}
ngOnInit() {
//get the user token from firebase auth
firebase.auth().currentUser.getIdToken(true).then((idTokenData) => {
//assign the token to the property
this.idToken = idTokenData;
//call your http service upon ASYNC return of the token
this.service.myHttpPost(data, this.idToken).subscribe(returningdata => {
console.log(returningdata)
});
}).catch((error) => {
// Handle error
console.log(error);
});
}
}
//#### YOUR SERVICE #####
//import of http service
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MyServiceClass {
constructor(private http: HttpClient) { }
//your myHttpPost method your calling from your ts file
myHttpPost(data: object, token: string): Observable<any> {
//defining your header - token is added to Authorization Bearer key with space between Bearer, so it can be split in your Google Cloud Function
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
})
}
//define your Google Cloud Function end point your get from creating your GCF
const endPoint = ' https://us-central1-your-app.cloudfunctions.net/doSomethingCool';
return this.http.post<string>(endPoint, data, httpOptions);
}
}
//#### YOUR GOOGLE CLOUD FUNCTION 'GCF' #####
//your imports
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({origin: true});
exports.doSomethingCool = functions.https.onRequest((req, res) => {
//cross origin middleware
cors(req, res, () => {
//get the token from the service header by splitting the Bearer in the Authorization header
const tokenId = req.get('Authorization').split('Bearer ')[1];
//verify the authenticity of token of the user
admin.auth().verifyIdToken(tokenId)
.then((decodedToken) => {
//get the user uid if you need it.
const uid = decodedToken.uid;
//do your cool stuff that requires authentication of the user here.
//end of authorization
})
.catch((error) => {
console.log(error);
});
//end of cors
})
//end of function
})