Firebase 身份验证与 AWS Cognito [英] Firebase authentication vs AWS Cognito

本文介绍了Firebase 身份验证与 AWS Cognito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用 API Gateway 和 Lambda 在 AWS 上构建移动和网络应用程序,目前正在评估是否应该使用 AWS CognitoFirebase 身份验证.

We are building a mobile and web app on AWS using API Gateway and Lambda and are currently evaluating if we should use AWS Cognito or Firebase Auth.

AWS Cognito 很好地集成到 API Gateway 和 Lamdba 中,例如只有经过身份验证的用户才能执行某些 API 调用.如果我们改用 Firebase 身份验证,是否可以达到相同的行为?有什么好的或坏的经验吗?

AWS Cognito integrates nicely into API Gateway and Lamdba e.g. only authenticated users can execute certain API calls. Can the same behaviour be reached if we use Firebase Authentication instead? Any good or bad experience with this?

推荐答案

我们正在做同样的事情.

We are doing the same.

我们从 Cognito 开始,后来迁移到 Firebase,因为我们对 AWS Android SDK 使用 Google 和 Facebook 实现身份验证流程的方式不满意:代码很旧,它使用了已弃用的方法,并且通常需要重写.另一方面,Firebase 身份验证显然可以无缝运行.

We started with Cognito but moved to Firebase because we were not satisfied with the way AWS Android SDK implements the authentication flow with Google and Facebook: the code is quite old, it makes use of deprecated methods and generally requires rewriting. On the other hand, Firebase authentication is obviously working seamlessly.

当您不使用 Cognito 时,您需要在 AWS API Gateway 中实现您的自定义身份验证器,这非常容易,并且在 https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-网关/.令牌验证的 Firebase 说明位于 https://firebase.google.com/docs/auth/admin/verify-id-tokens

When you don't use Cognito, you need to implement your custom authenticator in AWS API Gateway which is quite easy and is described in https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/. Firebase instructions for token validation are in https://firebase.google.com/docs/auth/admin/verify-id-tokens

以下是我的验证器代码的摘录:

The following is an excerpt of my authenticator's code:

'use strict';

// Firebase initialization
// console.log('Loading function');
const admin = require("firebase-admin");
admin.initializeApp({
  credential: admin.credential.cert("xxx.json"),
  databaseURL: "https://xxx.firebaseio.com"
});
// Standard AWS AuthPolicy - don't touch !!
...
// END Standard AWS AuthPolicy - don't touch !!

exports.handler = (event, context, callback) => {
    // console.log('Client token:', event.authorizationToken);
    // console.log('Method ARN:', event.methodArn);

    // validate the incoming token
    // and produce the principal user identifier associated with the token

    // this is accomplished by Firebase Admin
    admin.auth().verifyIdToken(event.authorizationToken)
        .then(function(decodedToken) {
            let principalId = decodedToken.uid;
            // console.log(JSON.stringify(decodedToken));

            // if the token is valid, a policy must be generated which will allow or deny access to the client

            // if access is denied, the client will recieve a 403 Access Denied response
            // if access is allowed, API Gateway will proceed with the backend integration configured on the method that was called

            // build apiOptions for the AuthPolicy
            const apiOptions = {};
            const tmp = event.methodArn.split(':');
            const apiGatewayArnTmp = tmp[5].split('/');
            const awsAccountId = tmp[4];
            apiOptions.region = tmp[3];
            apiOptions.restApiId = apiGatewayArnTmp[0];
            apiOptions.stage = apiGatewayArnTmp[1];
            
            const method = apiGatewayArnTmp[2];
            let resource = '/'; // root resource
            if (apiGatewayArnTmp[3]) {
                resource += apiGatewayArnTmp[3];
            }
            

            // this function must generate a policy that is associated with the recognized principal user identifier.
            // depending on your use case, you might store policies in a DB, or generate them on the fly

            // keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)
            // and will apply to subsequent calls to any method/resource in the RestApi
            // made with the same token

            // the policy below grants access to all resources in the RestApi
            const policy = new AuthPolicy(principalId, awsAccountId, apiOptions);
            policy.allowAllMethods();
            // policy.denyAllMethods();
            // policy.allowMethod(AuthPolicy.HttpVerb.GET, "/users/username");

            // finally, build the policy and exit the function
            callback(null, policy.build());
        })
        .catch(function(error) {
            // Firebase throws an error when the token is not valid
            // you can send a 401 Unauthorized response to the client by failing like so:
            console.error(error);
            callback("Unauthorized");
        });
};

我们尚未投入生产,但对身份验证器的测试表明,它在使用 Google、Facebook 和密码身份验证时运行正常,而且速度也非常快(60 - 200 毫秒).我能看到的唯一缺点是验证器 lambda 功能需要付费,而 Cognito 集成验证器是免费的.

We are not in production, yet, but tests on the authenticator show that it behaves correctly with Google, Facebook and password authentication and it is also very quick (60 - 200 ms). The only drawback I can see is that you will be charged for the authenticator lambda function, while the Cognito integrated authenticator is free.

近一年后更新

我不再使用 API Gateway 自定义身份验证器,主要是因为我无法使用 cloudformation 脚本自动部署它.我的解决方案是在一段时间内直接在 API 缓存令牌中进行身份验证,就像身份验证器一样,以避免过度验证.

I moved away from API Gateway custom authenticator, mainly because I've not been able to automate its deployment with cloudformation scripts. My solution is now to have authentication directly within the API caching tokens for some time, like the Authenticator does, so to avoid excessive validations.

这篇关于Firebase 身份验证与 AWS Cognito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆