it-source

Firebase 인증 vs AWS Cognito

criticalcode 2023. 7. 15. 10:15
반응형

Firebase 인증 vs AWS Cognito

우리는 API Gateway와 Lambda를 이용하여 AWS에 모바일과 웹 앱을 구축하고 있으며, 현재 AWS Cognito와 Firebase Auth 중 어느 쪽을 사용해야 할지 검토 중입니다.

AWS Cognito는 API Gateway 및 Lamdba와 원활하게 통합됩니다. 예를 들어 인증된 사용자만 특정 API 호출을 실행할 수 있습니다.대신 Firebase Authentication을 사용하면 동일한 동작에 도달할 수 있습니까?좋은 경험이나 나쁜 경험이 있습니까?

우리도 똑같이 하고 있어요.

우리는 Cognito에서 시작했지만 AWS Android SDK가 Google 및 Facebook에서 인증 흐름을 구현하는 방식에 만족하지 못해 Firebase로 이동했습니다. 코드가 상당히 오래되었고, 사용되지 않는 방법을 사용하며 일반적으로 다시 작성해야 합니다.반면에 Firebase 인증은 확실히 원활하게 작동합니다.

Cognito를 사용하지 않을 때는 AWS API Gateway에서 사용자 지정 인증자를 구현해야 합니다. 이는 https://aws.amazon.com/blogs/mobile/integrating-amazon-cognito-user-pools-with-api-gateway/ 에서 쉽게 설명할 수 있습니다.토큰 유효성 검사에 대한 Firebase 지침은 https://firebase.google.com/docs/auth/admin/verify-id-tokens 에 있습니다.

다음은 인증자 코드의 발췌본입니다.

'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");
        });
};

우리는 아직 생산 중은 아니지만, 오센티케이터에 대한 테스트 결과 구글, 페이스북 및 비밀번호 인증에서 올바르게 작동하고 매우 빠릅니다(60~200ms).제가 볼 수 있는 유일한 단점은 Cognito 통합 오센티케이터는 무료인 반면, 오센티케이터 람다 함수에 대한 요금이 부과된다는 것입니다.


거의 1년 후 업데이트

API Gateway Custom Authenticator를 사용하지 않게 된 것은 주로 클라우드 형성 스크립트를 사용하여 배포를 자동화할 수 없었기 때문입니다.이제 제 솔루션은 Authenticator처럼 API 캐싱 토큰 내에서 인증을 직접 수행하여 과도한 유효성 검사를 방지하는 것입니다.

TL;DR;파이어베이스 > Cognito

우리는 처음에 Cognito로 시작했지만, 마침내 연합 ID(예: Google 로그인, Facebook 로그인 등)를 사용할 때 끔찍한 냄새가 난다는 것을 깨달았습니다.Cognito User Pools(즉, 사용자 이름과 암호로 로그인/가입 허용)의 경우, 내장된 API Gateway Cognito User Pool Authorizer를 사용할 수 있으며 원활하게 작동합니다.사용자 지정 인증자를 직접 작성할 필요는 없습니다.

그러나 연합 ID를 지원하려면 API 게이트웨이의 인증을 IAM Auth로 변경한 다음 모든 클라이언트 sigv4가 요청에 서명하도록 해야 합니다. 이는 당사의 골칫거리이며 상당한 개발 시간이 소요되는 것으로 나타났습니다.옵션 2는 API 게이트웨이가 모든 클라이언트에 대한 API 호출 코드를 생성하도록 하는 것이었습니다.제 생각에 그것은 코그니토와의 번거로운 통합에 대한 증거입니다.

파이어베이스가 API 게이트웨이에 대한 사용자 지정 권한자를 통해 작업하고 있습니다.모든 고객(iOS, Android 및 웹)에게 쉬운 일이었습니다.API Gateway 엔드포인트는 람다 함수에 연결되어 엔드포인트를 호출하는 사용자를 대신하여 DynamoDB, S3 및 기타 웹 서비스와 통신할 수 있습니다.사용자 지정 권한 부여자가 JWT에서 전자 메일 주소를 반환했기 때문에 람다 함수는 호출하는 사용자가 누구인지 알고 있었습니다.

다음은 JWT의 사용자 이메일을 principalId로 반환하는 매우 기본적인 Firebase 사용자 지정 권한자입니다.

'use strict';
console.log('Loading function');

var admin = require('firebase-admin');
var serviceAccount = require('./my-secret-json.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://my-app.firebaseio.com'
});

exports.handler = (event, context, callback) => {
    var token = event.authorizationToken;

    if (token == null) {
        callback('Invalid token');
    }
    else {
        admin.auth().verifyIdToken(token)
            .then(function (decodedToken) {
                var email = decodedToken.email;
                var policy = generatePolicy(email);
                callback(null, policy);
            }).catch(function (error) {
                console.log(error);
                callback('Unauthorized'); 
            });
    }
};

var generatePolicy = function (email) {
    return {
        principalId: email,
        policyDocument: {
            Version: '2012-10-17',
            Statement: [
                {
                    Action: 'execute-api:Invoke',
                    Effect: email ? 'allow' : 'deny',
                    Resource: '*'
                }
            ]
        }
    };
}

그러면 다음을 사용할 수 있습니다.$context.authorizer.principalId사용자의 API 게이트웨이 매핑 템플릿에서 전자 메일을 검색하여 람다 X에 전달합니다.


처음에는 지연 시간이 문제가 될 것이라고 생각했지만, 실제로는 그렇지 않은 것 같습니다.모든 지연 시간은 콜드 스타트로 인해 호출되는 람다의 지연 시간 때문입니다.저는 인가 람다가 다른 람다보다 훨씬 오래 산다는 것을 알아챘습니다.


이 람다는 모든 백엔드 요청에 대해 호출됩니다.하지만 다음과 같은 몇 가지 사항이 있습니다.

  1. 캐싱은 각 JWT에 대해 1시간 동안 활성화되므로 통화가 크게 간소화됩니다.
  2. 람다는 지속적으로 호출되므로 콜드 스타트가 없어야 하며,
  3. 첫 번째 MILLION 람다 요청/월은 무료이며, 그 이후에는 100만 요청/월마다 $0.20입니다.따라서 API가 매달 Billion이라고 불리는 경우가 아니라면 엄청난 비용이 발생하지 않을 것입니다.

AWS 설명서가 상당히 혼란스럽습니다.다양한 인증 단계에 대한 콜백 시스템은 Firebase에서 더 잘 문서화되어 있습니다.결과적으로 코드를 더 깨끗하게 하고 인증 흐름을 더 잘 제어할 수 있습니다.또한 Firebase 사용자 인터페이스는 보다 사용자 친화적입니다.컨텐츠 공급자와 동기화 어댑터를 사용할 계획이라면 로컬과 원격(Firebase) DB 간에 데이터 동기화를 위한 간단한 방법이 있을 것이므로 Firebase를 사용하는 것이 좋습니다.

다른 인증 서비스 공급자로 이동하기로 결정한 경우 거래 차단기는 모든 세부 정보를 포함한 사용자를 내보낼 수 있는 기능입니다.

Firebase에서는 가능하지만 AWS Cognitio에서는 사용할 수 없습니다!연중 아무 때나 입력할 수 있지만 절대로 나갈 수 없습니다 :).https://forums.aws.amazon.com/thread.jspa?threadID=296932

aws cognito는 파이어베이스보다 사용자를 인증하는 더 많은 방법을 제공합니다.특히 게임을 만들고 있다면 구글과 iOS 게임 센터를 통해 로그인할 수 있는 기능을 제공합니다.게임 센터가 제공하는 동기화 리더 보드 및 성과를 제공합니다.자동 상태 동기화 기능은 Cognito에 있습니다.하지만 확실히, 그것은 매우 혼란스럽습니다.구현하는 데 너무 많은 시간이 걸립니다.반면에, 파이어베이스 인증은 구현이 매우 빠릅니다.

유니티를 사용하시는 경우를 대비하여 현재 유니티 SDK는 Cognito User Pool을 지원하지 않습니다. (즉, AWS 호스트 사용자 목록) 이 때문에 망설이고 있습니다.사실임을 확인한 제 게시물을 참조하십시오. 현재(2017년 6월 26일) 이 기능은 여전히 사용할 수 없으며 Unity 사용자의 주의가 부족할 수 있습니다.

그러나 로그인에 Firebase를 사용하는 경우 AWS 서비스를 사용하기 위해 해당 자격 증명에 대한 통합이 더 필요합니다.(S3와 DynamoDB를 사용하고 싶은데 로그인한 사용자만 사용할 수 있습니다.)이를 통해 가능한 한 빨리 시간과 불만을 줄이기 위해 모든 것을 Firebase로 옮겨야 한다는 것을 깨달았습니다. (실시간 DB는 S3/DynamoDB보다 더 비싸지만 Unity는 AWS Mobile을 대체할 수 있습니다.)분석)

AWS S3는 최근에 더 좋은 UI를 얻었는데, 구글 수준에 가깝다고 생각합니다.하지만 그 외에는 파이어베이스의 UI가 사용하기에 훨씬 더 즐겁다고 생각합니다.

또한 Firebase 인증은 무료이며 Cognito는 월간 활성 사용자 50,000명까지 무료입니다. (다음 50,000명은 0.0055달러입니다. 즉, MAU가 100,000개인 경우 50000*0.0055 = 275USD https://aws.amazon.com/cognito/pricing/)

한 가지 더, AWS.NET 문서는 제가 보기에 읽기/검색하기에 악몽입니다.

언급URL : https://stackoverflow.com/questions/40649605/firebase-authentication-vs-aws-cognito

반응형