0
0

More than 1 year has passed since last update.

AppAuth for Androidを用いてHUAWEI IDログインを実装する

Last updated at Posted at 2022-02-02

前置き

HUAWEI IDログインを実装するのに、よく使われているのはHMS Account Kitを導入する方法です。しかし、この方法ではAndroid端末にHMS Coreがインストールされていることが前提条件になっています。幸い、HUAWEI IDログインではOAuth 2.0が提供されているので、AppAuth for Androidを利用すれば、HMS CoreがインストールされていないAndroid端末でもHUAWEI IDログインが使えます。

AppAuth for Androidを利用するメリット

  1. HMS Coreがいりません。
  2. 独自実装より楽です。

AppAuth for Androidの導入方法

AppAuth for Androidの使い方で基本的な使い方を解説しました。ここではHUAWEI IDログインに特化した導入方法を説明します。

AppGallery Connectでプロジェクトを作成

“HMS Account Kit実装入門”の“前準備”に書かれた手順に従って、プロジェクトを作成してください。ただし、agconnect-services.jsonをappフォルダに配置する必要はありません。

OAuth 2.0 client ID

クライアントIDは[Project setting]→[General Information]→[App information]→[OAuth 2.0 client ID]→[Client ID]にあります。

ライブラリの導入

appモジュールのbuild.gradleに
1. AppAuth for Androidnet.openid:appauth
2. JWT Decoding library for Androidcom.auth0.android:jwtdecode
を追加します。

build.gradle
// AppAuth SDK:最新バージョンはhttps://search.maven.org/artifact/net.openid/appauth
implementation 'net.openid:appauth:0.11.1'
// For decode ID Token:最新バージョンはhttps://mvnrepository.com/artifact/com.auth0.android/jwtdecode
implementation 'com.auth0.android:jwtdecode:2.0.0'

AndroidManifest.xmlの編集

AndroidManifest.xmlに次のようにリダイレクト用のactivityを追加します。

AndroidManifest.xml
...
<activity
        android:name="net.openid.appauth.RedirectUriReceiverActivity"
        tools:node="replace">
    <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:scheme="com.huawei.apps.{OAuth 2.0 client ID}"/>
    </intent-filter>
</activity>
...

AuthStateとAuthorizationServiceConfigurationを用意

空のAuthStateとAuthorizationServiceConfigurationを生成します。

private val appAuthState: AuthState = AuthState.jsonDeserialize("{}")
private val config = AuthorizationServiceConfiguration(
    Uri.parse("https://oauth-login.cloud.huawei.com/oauth2/v3/authorize"),
    Uri.parse("https://oauth-login.cloud.huawei.com/oauth2/v3/token")
)

サインイン

サインイン画面を表示

  1. AuthorizationRequestを生成します。
  2. スコープを設定します。
  3. AuthorizationServiceのgetAuthorizationRequestIntentで、サインインのIntentを作ります。
  4. startActivityForResultでサインインのIntentを起動します。
fun signIn() {
    val authorizationRequest = AuthorizationRequest
        .Builder(
            config,
            {OAuth 2.0 client ID},
            ResponseTypeValues.CODE,
            Uri.parse(com.huawei.apps.{OAuth 2.0 client ID}:/oauth2redirect)
        )
        .setScope({例:openid email profile})
        .build()
    val intent = AuthorizationService(context).getAuthorizationRequestIntent(authorizationRequest)
    startActivityForResult(intent, requestCode)
}

サインインの認証結果を取得

  1. onActivityResultでサインインの認証結果を受け取ります。
  2. AuthStateを更新します。

認証成功の条件
AuthorizationResponseが空ではなく、かつAuthorizationExceptionが空である

認証失敗の条件
AuthorizationResponseが空、またはAuthorizationExceptionが空ではない

fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    val authorizationResponse = AuthorizationResponse.fromIntent(data)
    val exception = AuthorizationException.fromIntent(data)
    appAuthState.update(authorizationResponse, exception)

    if (exception != null || authorizationResponse == null) {
        // 認証失敗
    } else {
        // 認証成功
    }
}

各トークンを取得

  1. AuthorizationResponseを使ってトークンを要求します。
  2. (1)のレスポンスを使ってAuthStateを更新します。
  3. AuthStateのaccessTokenにアクセストークンが入っています。
  4. AuthStateのidTokenにIDトークンが入っています。
AuthorizationService(context)
    .performTokenRequest(authorizationResponse.createTokenExchangeRequest()) { tokenResponse, authorizationException ->
        appAuthState.update(tokenResponse, authorizationException)
        tokenResponse?.let {
            // アクセストークン=appAuthState.accessToken
            // IDトークン=appAuthState.idToken
        }
    }

IDトークンをユーザー情報に変換

JWTでIDトークンを解凍したら、次のユーザー情報が取得できます。

val jwt = JWT(idToken)
// Open ID
val openId = jwt.subject
// 姓名
val name = jwt.claims["display_name"]?.asString()
// プロフィール画像のURL
val pictureUrl = jwt.claims["picture"]?.asString()
// メールアドレス
val email = jwt.claims["email"]?.asString()
// メールアドレスは認証済みかどうか
val emailVerified = jwt.claims["email_verified"]?.asBoolean()

GitHub

AppAuthDemo(Huawei Google)

参考

AppAuth for Android
AppAuth for Androidを用いてソーシャルログインを実装する
Accessing Account Kit Using AppAuth
HMS Account Kit

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0