با Firebase در Android با استفاده از یک سیستم احراز هویت سفارشی احراز هویت
با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
میتوانید با تغییر سرور احراز هویت خود برای تولید نشانههای امضا شده سفارشی زمانی که کاربر با موفقیت وارد سیستم میشود، Firebase Authentication با یک سیستم احراز هویت سفارشی ادغام کنید. برنامه شما این نشانه را دریافت میکند و از آن برای احراز هویت با Firebase استفاده میکند.
در فایل Gradle ماژول (سطح برنامه) خود (معمولا <project>/<app-module>/build.gradle.kts یا <project>/<app-module>/build.gradle )، وابستگی را برای کتابخانه Firebase Authentication برای Android اضافه کنید. توصیه میکنیم از Firebase Android BoM برای کنترل نسخهسازی کتابخانه استفاده کنید.
dependencies{// Import the BoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.2.0"))// Add the dependency for the Firebase Authentication library// When using the BoM, you don't specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-auth")}
با استفاده از Firebase Android BoM ، برنامه شما همیشه از نسخههای سازگار کتابخانههای Firebase Android استفاده میکند.
(جایگزین) وابستگی های کتابخانه Firebase را بدون استفاده از BoM اضافه کنید
اگر تصمیم گرفتید از Firebase BoM استفاده نکنید، باید هر نسخه کتابخانه Firebase را در خط وابستگی آن مشخص کنید.
توجه داشته باشید که اگر از چندین کتابخانه Firebase در برنامه خود استفاده می کنید، ما قویاً توصیه می کنیم از BoM برای مدیریت نسخه های کتابخانه استفاده کنید، که تضمین می کند همه نسخه ها سازگار هستند.
dependencies{// Add the dependency for the Firebase Authentication library// When NOT using the BoM, you must specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-auth:24.0.1")}
هنگام راه اندازی فعالیت خود، بررسی کنید که آیا کاربر در حال حاضر وارد سیستم شده است یا خیر:
Kotlin
publicoverridefunonStart(){super.onStart()// Check if user is signed in (non-null) and update UI accordingly.valcurrentUser=auth.currentUserupdateUI(currentUser)}
@OverridepublicvoidonStart(){super.onStart();// Check if user is signed in (non-null) and update UI accordingly.FirebaseUsercurrentUser=mAuth.getCurrentUser();updateUI(currentUser);}
وقتی کاربران وارد برنامه شما میشوند، اعتبار ورود به سیستم (به عنوان مثال، نام کاربری و رمز عبور آنها) را به سرور احراز هویت خود ارسال کنید. سرور شما اعتبارنامه ها را بررسی می کند و در صورت معتبر بودن یک توکن سفارشی برمی گرداند.
پس از اینکه رمز سفارشی را از سرور احراز هویت خود دریافت کردید، آن را به signInWithCustomToken ارسال کنید تا وارد کاربر شود:
Kotlin
customToken?.let{auth.signInWithCustomToken(it).addOnCompleteListener(this){task->
if(task.isSuccessful){// Sign in success, update UI with the signed-in user's informationLog.d(TAG,"signInWithCustomToken:success")valuser=auth.currentUserupdateUI(user)}else{// If sign in fails, display a message to the user.Log.w(TAG,"signInWithCustomToken:failure",task.exception)Toast.makeText(baseContext,"Authentication failed.",Toast.LENGTH_SHORT,).show()updateUI(null)}}}
mAuth.signInWithCustomToken(mCustomToken).addOnCompleteListener(this,newOnCompleteListener<AuthResult>(){@OverridepublicvoidonComplete(@NonNullTask<AuthResult>task){if(task.isSuccessful()){// Sign in success, update UI with the signed-in user's informationLog.d(TAG,"signInWithCustomToken:success");FirebaseUseruser=mAuth.getCurrentUser();updateUI(user);}else{// If sign in fails, display a message to the user.Log.w(TAG,"signInWithCustomToken:failure",task.getException());Toast.makeText(CustomAuthActivity.this,"Authentication failed.",Toast.LENGTH_SHORT).show();updateUI(null);}}});
اگر ورود به سیستم با موفقیت انجام شد، AuthStateListener میتوانید از روش getCurrentUser برای دریافت اطلاعات حساب کاربر استفاده کنید.
مراحل بعدی
پس از اینکه کاربر برای اولین بار وارد سیستم شد، یک حساب کاربری جدید ایجاد میشود و به اعتبارنامهها (یعنی نام کاربری و رمز عبور، شماره تلفن یا اطلاعات ارائهدهنده تاییدیه) مرتبط میشود که کاربر با آن وارد شده است. این حساب جدید بهعنوان بخشی از پروژه Firebase شما ذخیره میشود و میتوان از آن برای شناسایی کاربر در همه برنامههای پروژه شما، صرف نظر از نحوه ورود کاربر به سیستم استفاده کرد.
در برنامه های خود، می توانید اطلاعات اولیه نمایه کاربر را از شی FirebaseUser دریافت کنید. به مدیریت کاربران مراجعه کنید.
در قوانین امنیتیFirebase Realtime Database و Cloud Storage خود، میتوانید شناسه کاربری منحصر به فرد کاربر واردشده به سیستم را از متغیر auth دریافت کنید و از آن برای کنترل دادههایی که کاربر میتواند به آن دسترسی داشته باشد استفاده کنید.
تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-09-04 بهوقت ساعت هماهنگ جهانی."],[],[],null,["You can integrate Firebase Authentication with a custom authentication system by\nmodifying your authentication server to produce custom signed tokens when a user\nsuccessfully signs in. Your app receives this token and uses it to authenticate\nwith Firebase.\n\nBefore you begin\n\n1. If you haven't already, [add Firebase to your Android project](/docs/android/setup).\n2. In your **module (app-level) Gradle file** (usually `\u003cproject\u003e/\u003capp-module\u003e/build.gradle.kts` or `\u003cproject\u003e/\u003capp-module\u003e/build.gradle`), add the dependency for the Firebase Authentication library for Android. We recommend using the [Firebase Android BoM](/docs/android/learn-more#bom) to control library versioning. \n\n ```carbon\n dependencies {\n // Import the BoM for the Firebase platform\n implementation(platform(\"com.google.firebase:firebase-bom:34.2.0\"))\n\n // Add the dependency for the Firebase Authentication library\n // When using the BoM, you don't specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-auth\")\n }\n ```\n\n By using the [Firebase Android BoM](/docs/android/learn-more#bom),\n your app will always use compatible versions of Firebase Android libraries.\n *(Alternative)*\n Add Firebase library dependencies *without* using the BoM\n\n If you choose not to use the Firebase BoM, you must specify each Firebase library version\n in its dependency line.\n\n **Note that if you use *multiple* Firebase libraries in your app, we strongly\n recommend using the BoM to manage library versions, which ensures that all versions are\n compatible.** \n\n ```groovy\n dependencies {\n // Add the dependency for the Firebase Authentication library\n // When NOT using the BoM, you must specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-auth:24.0.1\")\n }\n ```\n3. Get your project's server keys:\n 1. Go to the [Service Accounts](https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk) page in your project's settings.\n 2. Click *Generate New Private Key* at the bottom of the *Firebase Admin SDK* section of the *Service Accounts* page.\n 3. The new service account's public/private key pair is automatically saved on your computer. Copy this file to your authentication server.\n\nAuthenticate with Firebase\n\n1. In your sign-in activity's `onCreate` method, get the shared instance of the `FirebaseAuth` object: \n\n Kotlin \n\n ```kotlin\n private lateinit var auth: FirebaseAuth\n // ...\n // Initialize Firebase Auth\n auth = Firebase.auth \n https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt#L27-L28\n ```\n\n Java \n\n ```java\n private FirebaseAuth mAuth;\n // ...\n // Initialize Firebase Auth\n mAuth = FirebaseAuth.getInstance();https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/CustomAuthActivity.java#L48-L49\n ```\n2. When initializing your Activity, check to see if the user is currently signed in: \n\n Kotlin \n\n ```kotlin\n public override fun onStart() {\n super.onStart()\n // Check if user is signed in (non-null) and update UI accordingly.\n val currentUser = auth.currentUser\n updateUI(currentUser)\n }https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt#L33-L38\n ```\n\n Java \n\n ```java\n @Override\n public void onStart() {\n super.onStart();\n // Check if user is signed in (non-null) and update UI accordingly.\n FirebaseUser currentUser = mAuth.getCurrentUser();\n updateUI(currentUser);\n }https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/CustomAuthActivity.java#L54-L60\n ```\n3. When users sign in to your app, send their sign-in credentials (for example, their username and password) to your authentication server. Your server checks the credentials and returns a [custom token](/docs/auth/admin/create-custom-tokens) if they are valid.\n4. After you receive the custom token from your authentication server, pass it to `signInWithCustomToken` to sign in the user: \n\n Kotlin \n\n ```kotlin\n customToken?.let {\n auth.signInWithCustomToken(it)\n .addOnCompleteListener(this) { task -\u003e\n if (task.isSuccessful) {\n // Sign in success, update UI with the signed-in user's information\n Log.d(TAG, \"signInWithCustomToken:success\")\n val user = auth.currentUser\n updateUI(user)\n } else {\n // If sign in fails, display a message to the user.\n Log.w(TAG, \"signInWithCustomToken:failure\", task.exception)\n Toast.makeText(\n baseContext,\n \"Authentication failed.\",\n Toast.LENGTH_SHORT,\n ).show()\n updateUI(null)\n }\n }\n }https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt#L44-L63\n ```\n\n Java \n\n ```java\n mAuth.signInWithCustomToken(mCustomToken)\n .addOnCompleteListener(this, new OnCompleteListener\u003cAuthResult\u003e() {\n @Override\n public void onComplete(@NonNull Task\u003cAuthResult\u003e task) {\n if (task.isSuccessful()) {\n // Sign in success, update UI with the signed-in user's information\n Log.d(TAG, \"signInWithCustomToken:success\");\n FirebaseUser user = mAuth.getCurrentUser();\n updateUI(user);\n } else {\n // If sign in fails, display a message to the user.\n Log.w(TAG, \"signInWithCustomToken:failure\", task.getException());\n Toast.makeText(CustomAuthActivity.this, \"Authentication failed.\",\n Toast.LENGTH_SHORT).show();\n updateUI(null);\n }\n }\n });https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/CustomAuthActivity.java#L65-L82\n ```\n If sign-in succeeds, the `AuthStateListener` you can use the `getCurrentUser` method to get the user's account data.\n\nNext steps\n\nAfter a user signs in for the first time, a new user account is created and\nlinked to the credentials---that is, the user name and password, phone\nnumber, or auth provider information---the user signed in with. This new\naccount is stored as part of your Firebase project, and can be used to identify\na user across every app in your project, regardless of how the user signs in.\n\n- In your apps, you can get the user's basic profile information from the\n [`FirebaseUser`](/docs/reference/android/com/google/firebase/auth/FirebaseUser) object. See [Manage Users](/docs/auth/android/manage-users).\n\n- In your Firebase Realtime Database and Cloud Storage\n [Security Rules](/docs/database/security/user-security), you can\n get the signed-in user's unique user ID from the `auth` variable,\n and use it to control what data a user can access.\n\nYou can allow users to sign in to your app using multiple authentication\nproviders by [linking auth provider credentials to an\nexisting user account.](/docs/auth/android/account-linking)\n\nTo sign out a user, call [`signOut`](/docs/reference/android/com/google/firebase/auth/FirebaseAuth#signOut()): \n\nKotlin \n\n```kotlin\nFirebase.auth.signOut()https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MainActivity.kt#L415-L415\n```\n\nJava \n\n```java\nFirebaseAuth.getInstance().signOut();https://github.com/firebase/snippets-android/blob/b694d4dbd411d31be39655f47691c3e9f3529b03/auth/app/src/main/java/com/google/firebase/quickstart/auth/MainActivity.java#L501-L501\n```"]]