在 Android 上使用 GitHub 进行身份验证
GitHub是超过6500 万开发人员共同塑造软件未来的地方。为开源社区做出贡献,管理您的 Git 存储库,像专业人士一样审查代码,跟踪错误和功能,支持您的 CI/CD 和 DevOps 工作流程,并在提交代码之前保护代码。因此,在本文中,我们将讨论如何借助 Firebase 用户身份验证在您的 Android 应用程序中使用 GitHub 进行身份验证。
使用 GitHub 进行 Firebase 用户身份验证的步骤
第1步:
在 android studio 中创建一个新项目或通过您想要通过 GitHub 对用户进行身份验证并将 firebase 添加到该 android 应用程序的方式打开任何现有项目。在应用程序中添加 firebase 的步骤。
第2步:
转到您的 firebase 控制台,转到您的应用程序,然后导航到项目设置并添加已连接应用程序的类似指纹的 SHA1。要找到 SHA1,请转到 Gradle(android-studio 窗口的右侧)> your-application-name > Tasks > Android > signatureReport(双击它)
Note: Make sure to add google-services.json in your application, otherwise, download it from the project settings of the firebase console and add it to your application.
第 3 步:
返回 firebase 控制台中的应用程序,导航到身份验证(firebase 的左侧面板),然后转到登录方法启用 GitHub 提供程序。
现在,我们需要客户端 ID和客户端机密。为此,在 GitHub 上将您的应用程序注册为开发人员应用程序,并获取您的应用程序的 OAuth 2.0 客户端 ID 和客户端密钥。要注册您的应用程序,请输入应用程序名称,输入应用程序的网站主页 URL(这里我提供与授权回调 URL 相同的 URL),并简要提供应用程序描述。
Note: Make sure your Firebase OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is set as your Authorization callback URL in your app’s settings page on your GitHub app’s config.
获取您的可授权回调 URL ,如下图所示。
单击注册应用程序。您将获得您的Client ID和Client secret ,将它们复制并粘贴到 firebase 控制台(在登录方法下),然后单击保存按钮以启用 GitHub。
第四步:
回到安卓工作室。使用 Firebase Android BoM 在 build.gradle (模块:your-application-name.app)中为 Firebase Authentication Android 库添加依赖项。
dependencies {
// Import the BoM for the Firebase platform
implementation platform(‘com.google.firebase:firebase-bom:28.0.1’)
// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don’t specify versions in Firebase library dependencies
implementation ‘com.google.firebase:firebase-auth-ktx’
}
通过使用Firebase Android BoM ,您的应用将始终使用Firebase Android 库的兼容版本。
步骤 5:使用 MainActivity 文件
导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。
XML
Kotlin
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.OAuthProvider
class MainActivity : AppCompatActivity() {
private lateinit var firebaseUser: FirebaseUser
private lateinit var loginBtn: Button
private lateinit var githubEdit: EditText
// firebaseAuth variable to be initialized later
private lateinit var auth: FirebaseAuth
// an instance of an OAuthProvider using its Builder
// with the provider ID github.com
private val provider = OAuthProvider.newBuilder("github.com")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loginBtn = findViewById(R.id.github_login_btn)
githubEdit = findViewById(R.id.githubId)
// initializing auth
auth = FirebaseAuth.getInstance()
// Target specific email with login hint.
provider.addCustomParameter("login", githubEdit.text.toString())
// Request read access to a user's email addresses.
// This must be preconfigured in the app's API permissions.
val scopes: ArrayList = object : ArrayList() {
init {
add("user:email")
}
}
provider.scopes = scopes
// call signInWithGithubProvider() method
// after clicking login Button
loginBtn.setOnClickListener {
if (TextUtils.isEmpty(githubEdit.text.toString())) {
Toast.makeText(this, "Enter your github id", Toast.LENGTH_LONG).show()
} else {
signInWithGithubProvider()
}
}
}
// To check if there is a pending result, call pendingAuthResult
private fun signInWithGithubProvider() {
// There's something already here! Finish the sign-in for your user.
val pendingResultTask: Task? = auth.pendingAuthResult
if (pendingResultTask != null) {
pendingResultTask
.addOnSuccessListener {
// User is signed in.
Toast.makeText(this, "User exist", Toast.LENGTH_LONG).show()
}
.addOnFailureListener {
// Handle failure.
Toast.makeText(this, "Error : $it", Toast.LENGTH_LONG).show()
}
} else {
auth.startActivityForSignInWithProvider( /* activity= */this, provider.build())
.addOnSuccessListener(
OnSuccessListener {
// User is signed in.
// retrieve the current user
firebaseUser = auth.currentUser!!
// navigate to HomePageActivity after successful login
val intent = Intent(this, HomePageActivity::class.java)
// send github user name from MainActivity to HomePageActivity
intent.putExtra("githubUserName", firebaseUser.displayName)
this.startActivity(intent)
Toast.makeText(this, "Login Successfully", Toast.LENGTH_LONG).show()
})
.addOnFailureListener(
OnFailureListener {
// Handle failure.
Toast.makeText(this, "Error : $it", Toast.LENGTH_LONG).show()
})
}
}
}
XML
Kotlin
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class HomePageActivity : AppCompatActivity() {
var userName = ""
private lateinit var githubUserName: TextView
private lateinit var logoutBtn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page)
githubUserName = findViewById(R.id.id)
logoutBtn = findViewById(R.id.logOut)
userName = intent.getStringExtra("githubUserName")!!
githubUserName.text = userName
logoutBtn.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
}
}
}
转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
科特林
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.AuthResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.OAuthProvider
class MainActivity : AppCompatActivity() {
private lateinit var firebaseUser: FirebaseUser
private lateinit var loginBtn: Button
private lateinit var githubEdit: EditText
// firebaseAuth variable to be initialized later
private lateinit var auth: FirebaseAuth
// an instance of an OAuthProvider using its Builder
// with the provider ID github.com
private val provider = OAuthProvider.newBuilder("github.com")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loginBtn = findViewById(R.id.github_login_btn)
githubEdit = findViewById(R.id.githubId)
// initializing auth
auth = FirebaseAuth.getInstance()
// Target specific email with login hint.
provider.addCustomParameter("login", githubEdit.text.toString())
// Request read access to a user's email addresses.
// This must be preconfigured in the app's API permissions.
val scopes: ArrayList = object : ArrayList() {
init {
add("user:email")
}
}
provider.scopes = scopes
// call signInWithGithubProvider() method
// after clicking login Button
loginBtn.setOnClickListener {
if (TextUtils.isEmpty(githubEdit.text.toString())) {
Toast.makeText(this, "Enter your github id", Toast.LENGTH_LONG).show()
} else {
signInWithGithubProvider()
}
}
}
// To check if there is a pending result, call pendingAuthResult
private fun signInWithGithubProvider() {
// There's something already here! Finish the sign-in for your user.
val pendingResultTask: Task? = auth.pendingAuthResult
if (pendingResultTask != null) {
pendingResultTask
.addOnSuccessListener {
// User is signed in.
Toast.makeText(this, "User exist", Toast.LENGTH_LONG).show()
}
.addOnFailureListener {
// Handle failure.
Toast.makeText(this, "Error : $it", Toast.LENGTH_LONG).show()
}
} else {
auth.startActivityForSignInWithProvider( /* activity= */this, provider.build())
.addOnSuccessListener(
OnSuccessListener {
// User is signed in.
// retrieve the current user
firebaseUser = auth.currentUser!!
// navigate to HomePageActivity after successful login
val intent = Intent(this, HomePageActivity::class.java)
// send github user name from MainActivity to HomePageActivity
intent.putExtra("githubUserName", firebaseUser.displayName)
this.startActivity(intent)
Toast.makeText(this, "Login Successfully", Toast.LENGTH_LONG).show()
})
.addOnFailureListener(
OnFailureListener {
// Handle failure.
Toast.makeText(this, "Error : $it", Toast.LENGTH_LONG).show()
})
}
}
}
第 6 步:创建一个新的 Empty Activity
参考这篇文章在 Android Studio 中创建新活动并创建一个空活动。将活动命名为HomePageActivity。导航到app > res > layout > activity_home_page.xml并将以下代码添加到该文件中。下面是activity_home_page.xml文件的代码。
XML
转到HomePageActivity.kt文件并参考以下代码。下面是HomePageActivity.kt文件的代码。
科特林
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class HomePageActivity : AppCompatActivity() {
var userName = ""
private lateinit var githubUserName: TextView
private lateinit var logoutBtn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_page)
githubUserName = findViewById(R.id.id)
logoutBtn = findViewById(R.id.logOut)
userName = intent.getStringExtra("githubUserName")!!
githubUserName.text = userName
logoutBtn.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
this.startActivity(intent)
}
}
}
Note: Don’t forget to Revoke all user tokens. This option will be shown when your application is ready and run once. Or may you see this option earlier?
这是最终的输出。
输出: