Firebase 클라이언트 앱이 커스텀 백엔드 서버와 통신하는 경우 서버에 현재 로그인한 사용자를 식별해야 할 수 있습니다. 사용자를 안전하게 식별하려면 로그인이 정상적으로 이루어진 후에 HTTPS를 사용하여 사용자의 ID 토큰을 서버로 전송합니다. 그런 다음 서버에서 ID 토큰의 무결성과 진위를 검증하고 ID 토큰에서 uid를 가져옵니다. 이 방법으로 전송된 uid를 사용하면 현재 서버에 로그인한 사용자를 안전하게 식별할 수 있습니다.
시작하기 전에
Firebase Admin SDK로 ID 토큰을 검증하려면 서비스 계정이 있어야
합니다. 서비스 계정으로 Admin SDK를 초기화하는
자세한 방법은 Admin SDK 설정 안내를 참조하세요.
클라이언트에서 ID 토큰 검색
사용자 또는 기기가 로그인에 성공하면 Firebase는 이들을 고유하게 식별하는 해당 ID 토큰을 만들고 Firebase Realtime Database 및 Cloud Storage와 같은 여러 리소스에 대한 액세스를 허용합니다. 맞춤 백엔드 서버에서는 이 ID 토큰을
재사용하여 사용자 또는 기기를 식별할 수 있습니다. 클라이언트에서 ID 토큰을 검색하려면 다음과 같이 사용자가 로그인한 상태인지 확인하고 로그인한 사용자의 ID 토큰을 가져옵니다.
iOS+
Objective-C
FIRUser*currentUser=[FIRAuthauth].currentUser;[currentUsergetIDTokenForcingRefresh:YEScompletion:^(NSString*_NullableidToken,NSError*_Nullableerror){if(error){// Handle errorreturn;}// Send token to your backend via HTTPS// ...}];
Swift
let currentUser = FIRAuth.auth()?.currentUser
currentUser?.getIDTokenForcingRefresh(true) { idToken, error in
if let error = error {
// Handle error
return;
}
// Send token to your backend via HTTPS
// ...
}
Firebase.Auth.FirebaseUseruser=auth.CurrentUser;user.TokenAsync(true).ContinueWith(task=>{if(task.IsCanceled){Debug.LogError("TokenAsync was canceled.");return;}if(task.IsFaulted){Debug.LogError("TokenAsync encountered an error: "+task.Exception);return;}stringidToken=task.Result;// Send token to your backend via HTTPS// ...});
C++
firebase::auth::Useruser=auth->current_user();if(user.is_valid()){firebase::Future<std::string>idToken=user.GetToken(true);// Send token to your backend via HTTPS// ...}
웹
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
}).catch(function(error) {
// Handle error
});
ID 토큰이 확보되었으면 이 JWT를 백엔드로 전송하여 Firebase Admin SDK로 검증할 수 있습니다. Firebase가 기본적으로 지원하지 않는 언어로 서버가 작성된 경우 서드 파티 JWT 라이브러리를 사용할 수도 있습니다.
Firebase Admin SDK로 ID 토큰 검증
Firebase Admin SDK에는 ID 토큰 검증 및 디코딩을 담당하는 메소드가 내장되어
있습니다. 제공된 ID 토큰이 올바른 형식이고, 만료되지 않았으며, 정상적으로 서명된 경우 이 메서드는 디코딩된 ID 토큰을 반환합니다. 디코딩된 토큰에서 사용자 또는 기기의 uid를 확인할 수 있습니다.
Admin SDK 설정 안내에 따라 서비스 계정으로 Admin SDK를 초기화합니다. 그런 다음 verifyIdToken() 메서드를 사용하여 ID 토큰을 확인합니다.
Node.js
// idToken comes from the client appgetAuth().verifyIdToken(idToken).then((decodedToken)=>{constuid=decodedToken.uid;// ...}).catch((error)=>{// Handle error});
Java
// idToken comes from the client app (shown above)FirebaseTokendecodedToken=FirebaseAuth.getInstance().verifyIdToken(idToken);Stringuid=decodedToken.getUid();
Python
# id_token comes from the client app (shown above)decoded_token=auth.verify_id_token(id_token)uid=decoded_token['uid']
Go
client,err:=app.Auth(ctx)iferr!=nil{log.Fatalf("error getting Auth client: %v\n",err)}token,err:=client.VerifyIDToken(ctx,idToken)iferr!=nil{log.Fatalf("error verifying ID token: %v\n",err)}log.Printf("Verified ID token: %v\n",token)
ID 토큰 확인을 위해서는 프로젝트 ID가 필요합니다. Firebase Admin SDK는 다음 방법 중 하나를 사용하여 프로젝트 ID를 가져오려고 시도합니다.
SDK가 명시적인 projectId 앱 옵션을 사용해서 초기화된 경우 SDK가 해당 옵션의 값을 사용합니다.
SDK가 서비스 계정 사용자 인증 정보를 사용하여 초기화된 경우 SDK가 서비스 계정 JSON 객체의 project_id 필드를 사용합니다.
GOOGLE_CLOUD_PROJECT 환경 변수가 설정된 경우 SDK는 해당 값을 프로젝트 ID로 사용합니다. 이 환경 변수는 App Engine 및 Compute Engine과 같은 Google 인프라에서 실행되는 코드에 사용할 수 있습니다.
타사 JWT 라이브러리로 ID 토큰 검증
백엔드가 Firebase Admin SDK에서 지원하지 않는 언어로 작성되었더라도
ID 토큰을 검증할 수 있습니다. 우선 해당 언어의 서드 파티 JWT 라이브러리를 검색합니다. 그런 다음
ID 토큰의 헤더, 페이로드 및 서명을 검증합니다.
ID 토큰의 헤더가 다음과 같은 제약조건에 맞는지 확인합니다.
ID 토큰 헤더 클레임
alg
알고리즘
"RS256"
kid
키 ID
https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com에 나열된 공개 키 중 하나와 일치해야 합니다.
ID 토큰의 페이로드가 다음 제약조건에 맞는지 확인합니다.
ID 토큰 페이로드 클레임
exp
만료 시간
미래 시간이어야 합니다. UNIX 기점을 기준으로 측정한 시간(초)입니다.
iat
발급 시간
과거 시간이어야 합니다. UNIX 기점을 기준으로 측정한 시간(초)입니다.
aud
대상
Firebase 프로젝트 ID(Firebase 프로젝트의 고유 식별자)여야 합니다.
프로젝트 콘솔의 URL에서 확인할 수 있습니다.
iss
발급자
"https://securetoken.google.com/<projectId>"여야 합니다. 여기에서 <projectId>는 위 aud에 사용된 프로젝트 ID와 동일합니다.
sub
소유자
비어 있지 않은 문자열이어야 하며 사용자 또는 기기의 uid여야 합니다.
auth_time
인증 시간
과거 시간이어야 합니다. 사용자가 인증한 시간입니다.
마지막으로, 토큰의 kid 클레임에 해당하는 비공개 키로 ID 토큰이 서명되었는지 확인합니다. https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com에서 공개 키를 확인하고 JWT 라이브러리를 사용하여 서명을 검증합니다. 이 엔드포인트에서 보낸 응답의 Cache-Control 헤더에 있는 max-age 값을 사용하여 공개 키를 갱신할 시점을 파악합니다.
위 검증이 모두 성공하면 ID 토큰의 제목(sub)을 해당 사용자 또는 기기의 uid로 사용할 수 있습니다.
[null,null,["최종 업데이트: 2025-08-13(UTC)"],[],[],null,["\u003cbr /\u003e\n\nIf your Firebase client app communicates with a custom backend server, you\nmight need to identify the currently signed-in user on that server. To do so\nsecurely, after a successful sign-in, send the user's ID token to your server\nusing HTTPS. Then, on the server, verify the integrity and authenticity of the\nID token and retrieve the `uid` from it. You can use the `uid` transmitted in\nthis way to securely identify the currently signed-in user on your server.\n| **Note:** Many use cases for verifying ID tokens on the server can be accomplished by using Security Rules for the [Firebase Realtime Database](/docs/database/security) and [Cloud Storage](/docs/storage/security). See if those solve your problem before verifying ID tokens yourself.\n| **Warning:** The ID token verification methods included in the Firebase Admin SDKs are meant to verify ID tokens that come from the client SDKs, not the custom tokens that you create with the Admin SDKs. See [Auth tokens](/docs/auth/users#auth_tokens) for more information.\n\nBefore you begin\n\nTo verify ID tokens with the Firebase Admin SDK, you must have a service\naccount. Follow the [Admin SDK setup instructions](/docs/admin/setup) for\nmore information on how to initialize the Admin SDK with a service account.\n\nRetrieve ID tokens on clients\n\nWhen a user or device successfully signs in, Firebase creates a corresponding\nID token that uniquely identifies them and grants them access to several\nresources, such as Firebase Realtime Database and Cloud Storage. You can\nre-use that ID token to identify the user or device on your custom backend\nserver. To retrieve the ID token from the client, make sure the user is signed\nin and then get the ID token from the signed-in user: \n\niOS+\n\nObjective-C \n\n FIRUser *currentUser = [FIRAuth auth].currentUser;\n [currentUser getIDTokenForcingRefresh:YES\n completion:^(NSString *_Nullable idToken,\n NSError *_Nullable error) {\n if (error) {\n // Handle error\n return;\n }\n\n // Send token to your backend via HTTPS\n // ...\n }];\n\nSwift \n\n let currentUser = FIRAuth.auth()?.currentUser\n currentUser?.getIDTokenForcingRefresh(true) { idToken, error in\n if let error = error {\n // Handle error\n return;\n }\n\n // Send token to your backend via HTTPS\n // ...\n }\n\nAndroid \n\n FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();\n mUser.getIdToken(true)\n .addOnCompleteListener(new OnCompleteListener\u003cGetTokenResult\u003e() {\n public void onComplete(@NonNull Task\u003cGetTokenResult\u003e task) {\n if (task.isSuccessful()) {\n String idToken = task.getResult().getToken();\n // Send token to your backend via HTTPS\n // ...\n } else {\n // Handle error -\u003e task.getException();\n }\n }\n });\n\nUnity \n\n Firebase.Auth.FirebaseUser user = auth.CurrentUser;\n user.TokenAsync(true).ContinueWith(task =\u003e {\n if (task.IsCanceled) {\n Debug.LogError(\"TokenAsync was canceled.\");\n return;\n }\n\n if (task.IsFaulted) {\n Debug.LogError(\"TokenAsync encountered an error: \" + task.Exception);\n return;\n }\n\n string idToken = task.Result;\n\n // Send token to your backend via HTTPS\n // ...\n });\n\nC++ \n\n firebase::auth::User user = auth-\u003ecurrent_user();\n if (user.is_valid()) {\n firebase::Future\u003cstd::string\u003e idToken = user.GetToken(true);\n\n // Send token to your backend via HTTPS\n // ...\n }\n\nWeb \n\n firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {\n // Send token to your backend via HTTPS\n // ...\n }).catch(function(error) {\n // Handle error\n });\n\nOnce you have an ID token, you can send that JWT to your backend and validate\nit using the Firebase Admin SDK, or using a third-party JWT\nlibrary if your server is written in a language which Firebase does not\nnatively support.\n\nVerify ID tokens using the Firebase Admin SDK\n\nThe Firebase Admin SDK has a built-in method for verifying and decoding ID\ntokens. If the provided ID token has the correct format, is not expired, and is\nproperly signed, the method returns the decoded ID token. You can grab the\n`uid` of the user or device from the decoded token.\n| **Note:** This does not check whether or not the token has been revoked. See: [Detect ID token revocation](/docs/auth/admin/manage-sessions#detect_id_token_revocation).\n\nFollow the [Admin SDK setup instructions](/docs/admin/setup) to initialize\nthe Admin SDK with a service account. Then, use the `verifyIdToken()` method\nto verify an ID token: \n\nNode.js \n\n // idToken comes from the client app\n getAuth()\n .verifyIdToken(idToken)\n .then((decodedToken) =\u003e {\n const uid = decodedToken.uid;\n // ...\n })\n .catch((error) =\u003e {\n // Handle error\n });\n\nJava \n\n // idToken comes from the client app (shown above)\n FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);\n String uid = decodedToken.getUid();\n\nPython \n\n # id_token comes from the client app (shown above)\n\n decoded_token = auth.verify_id_token(id_token)\n uid = decoded_token['uid']\n\nGo \n\n client, err := app.Auth(ctx)\n if err != nil {\n \tlog.Fatalf(\"error getting Auth client: %v\\n\", err)\n }\n\n token, err := client.VerifyIDToken(ctx, idToken)\n if err != nil {\n \tlog.Fatalf(\"error verifying ID token: %v\\n\", err)\n }\n\n log.Printf(\"Verified ID token: %v\\n\", token) \n https://github.com/firebase/firebase-admin-go/blob/26dec0b7589ef7641eefd6681981024079b8524c/snippets/auth.go#L82-L92\n\nC# \n\n FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance\n .VerifyIdTokenAsync(idToken);\n string uid = decodedToken.Uid;\n\nID token verification requires a project ID. The Firebase Admin SDK attempts\nto obtain a project ID via one of the following methods:\n\n- If the SDK was initialized with an explicit `projectId` app option, the SDK uses the value of that option.\n- If the SDK was initialized with service account credentials, the SDK uses the `project_id` field of the service account JSON object.\n- If the `GOOGLE_CLOUD_PROJECT` environment variable is set, the SDK uses its value as the project ID. This environment variable is available for code running on Google infrastructure such as App Engine and Compute Engine.\n\nVerify ID tokens using a third-party JWT library\n\nIf your backend is in a language not supported by the Firebase Admin\nSDK, you can still verify ID tokens. First,\n[find a third-party JWT library for your language](https://jwt.io/). Then,\nverify the header, payload, and signature of the ID token.\n\nVerify the ID token's header conforms to the following constraints:\n\n| ID Token Header Claims |||\n|-------|-----------|------------------------------------------------------------------------------------------------------------------------------------------------|\n| `alg` | Algorithm | `\"RS256\"` |\n| `kid` | Key ID | Must correspond to one of the public keys listed at `https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com` |\n\nVerify the ID token's payload conforms to the following constraints:\n\n| ID Token Payload Claims |||\n|-------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------|\n| `exp` | Expiration time | Must be in the future. The time is measured in seconds since the UNIX epoch. |\n| `iat` | Issued-at time | Must be in the past. The time is measured in seconds since the UNIX epoch. |\n| `aud` | Audience | Must be your Firebase project ID, the unique identifier for your Firebase project, which can be found in the URL of that project's console. |\n| `iss` | Issuer | Must be `\"https://securetoken.google.com/\u003cprojectId\u003e\"`, where `\u003cprojectId\u003e` is the same project ID used for `aud` above. |\n| `sub` | Subject | Must be a non-empty string and must be the `uid` of the user or device. |\n| `auth_time` | Authentication time | Must be in the past. The time when the user authenticated. |\n\nFinally, ensure that the ID token was signed by the private key corresponding\nto the token's `kid` claim. Grab the public key from\n`https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com`\nand use a JWT library to verify the signature. Use the value of `max-age` in\nthe `Cache-Control` header of the response from that endpoint to know when to\nrefresh the public keys.\n\nIf all the above verifications are successful, you can use the subject (`sub`)\nof the ID token as the `uid` of the corresponding user or device."]]