깃허브 API를 통해 사용자가 깃허브 계정을 로그인하면 고유한 토큰
을 부여받을 수 있도록 암시적 인텐트
를 선언해줬다. 액션
과 카테고리
를 지정해주고 로그인에 성공한 경우 해당 액티비티로 돌아올 수 있도록 외부 스킴
을 설정해줬다.
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="github-auth"
android:scheme="com.example.github" />
</intent-filter>
private fun loginGithub() {
val loginUrl = Uri.Builder().scheme("https").authority("github.com")
.appendPath("login")
.appendPath("oauth")
.appendPath("authorize")
.appendQueryParameter("client_id", Key.GITHUB_CLIENT_ID)
.build()
CustomTabsIntent.Builder().build().also {
it.launchUrl(this, loginUrl)
}
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// todo getAccessToken
intent?.data?.getQueryParameter("code")?.let {
Log.d("AuthToken", it)
}
}
토큰
으로 사용자를 확인하고 정상적으로 판단되면 SharedPreference
에 사용자 정보를 저장한다. 어플리케이션을 재실행했을 때 로그인 페이지를 자동으로 넘어가기 위함이다.
private suspend fun getAccessToken(code: String) = launch(coroutineContext) {
try {
withContext(Dispatchers.IO) {
val response = RetrofitUtil.authApiService.getAccessToken(
clientId = Key.GITHUB_CLIENT_ID,
clientSecret = Key.GITHUB_CLIENT_SECRET,
code = code
)
if (response.isSuccessful) {
val accessToken = response.body()?.accessToken ?: "login"
if (accessToken.isNotEmpty()) {
authTokenProvider.setToken(accessToken)
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
class AuthTokenProvider(private val context: Context) {
fun setToken(token: String) {
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putString(Key.KEY_AUTH_TOKEN, token)
.apply()
}
val getToken: String?
get() = PreferenceManager.getDefaultSharedPreferences(context)
.getString(Key.KEY_AUTH_TOKEN, null)
}
로그인이 되어 있는 경우 로그인 화면을 자동으로 넘어가는 것을 볼 수 있다.