如何在 Kotlin 中使用 PKCE 实现 Spotify 的授权码

OET*_*e11 0 authentication android restful-authentication spotify kotlin

所以我想使用 Spotify 的 Web API。我已阅读一些文档,您需要使用 PKCE 实现身份验证代码。我不是 100% 确定如何做到这一点,并且可以使用一些帮助。

swe*_*eak 5

其中一种方法是使用Spotify 授权库。在开始之前,将以下依赖项添加到您的 Android 项目中:

// Spotify authorization
implementation 'com.spotify.android:auth:1.2.5'
Run Code Online (Sandbox Code Playgroud)

然后按照授权指南中的步骤开始编码:

1. 创建代码验证器并质询

这篇有用的文章有助于处理授权流程的初始加密部分。您可以快速阅读一下。

编码的第一步是创建一个companion object存储诸如CLIENT_ID代码验证器和代码质询之类的内容的文件:

// Spotify authorization
implementation 'com.spotify.android:auth:1.2.5'
Run Code Online (Sandbox Code Playgroud)

2. 构建授权URI

此步骤归结为使用AuthorizationRequest.BuilderAuthorizationClient为 Spotify 身份验证活动创建意图。

您将在此处提供指南中的所有必要参数:

companion object {
        const val CLIENT_ID = "your_client_id"
        const val REDIRECT_URI = "https://com.company.app/callback"

        val CODE_VERIFIER = getCodeVerifier()

        private fun getCodeVerifier(): String {
            val secureRandom = SecureRandom()
            val code = ByteArray(64)
            secureRandom.nextBytes(code)
            return Base64.encodeToString(
                code,
                Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
            )
        }

        fun getCodeChallenge(verifier: String): String {
            val bytes = verifier.toByteArray()
            val messageDigest = MessageDigest.getInstance("SHA-256")
            messageDigest.update(bytes, 0, bytes.size)
            val digest = messageDigest.digest()
            return Base64.encodeToString(
                digest,
                Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
            )
        }
    }
Run Code Online (Sandbox Code Playgroud)

3.您的应用程序将用户重定向到授权 URI

您可以在此处注册授权活动结果的回调,该回调将使用我们在上一步中创建的意图:

fun getLoginActivityCodeIntent(): Intent =
        AuthorizationClient.createLoginActivityIntent(
            activity,
            AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.CODE, REDIRECT_URI)
                .setScopes(
                    arrayOf(
                        "user-library-read", "user-library-modify",
                        "app-remote-control", "user-read-currently-playing"
                    )
                )
                .setCustomParam("code_challenge_method", "S256")
                .setCustomParam("code_challenge", getCodeChallenge(CODE_VERIFIER))
                .build()
        )
Run Code Online (Sandbox Code Playgroud)

在那里您将可以访问授权码- authorizationResponse.code。它将在下一步中使用。

4.您的应用程序将代码交换为访问令牌

在这里,我们必须为 Spotify 身份验证活动创建另一个意图。这与步骤 2 中的代码非常相似。getLoginActivityTokenIntent您必须提供从上一步中检索到的代码:

private val showLoginActivityCode = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->

        val authorizationResponse = AuthorizationClient.getResponse(result.resultCode, result.data)

        when (authorizationResponse.type) {
            AuthorizationResponse.Type.CODE ->
                // Here You will get the authorization code which you
                // can get with authorizationResponse.code
            AuthorizationResponse.Type.ERROR ->
                // Handle the Error
            else ->
                // Probably interruption
        }
    }


// Usage:
showLoginActivityCode.launch(getLoginActivityCodeIntent())
Run Code Online (Sandbox Code Playgroud)

然后创建回调:

fun getLoginActivityTokenIntent(code: String): Intent =
        AuthorizationClient.createLoginActivityIntent(
            activity,
            AuthorizationRequest.Builder(CLIENT_ID, AuthorizationResponse.Type.TOKEN, REDIRECT_URI)
                .setCustomParam("grant_type", "authorization_code")
                .setCustomParam("code", code)
                .setCustomParam("code_verifier", CODE_VERIFIER)
                .build()
        )
Run Code Online (Sandbox Code Playgroud)

现在授权部分就结束了 - 您已经获得了授权令牌的访问权限 - authorizationResponse.token。保存它,它将用于创建对 Spotify Web API 的请求。

5. 使用访问令牌访问 Spotify Web API

您可以开始使用 API。使用 Retrofit 的简单预览示例:

private val showLoginActivityToken = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->

        val authorizationResponse = AuthorizationClient.getResponse(result.resultCode, result.data)

        when (authorizationResponse.type) {
            AuthorizationResponse.Type.TOKEN -> {
                // Here You can get access to the authorization token
                // with authorizationResponse.token
            }
            AuthorizationResponse.Type.ERROR ->
                // Handle Error
            else ->
                // Probably interruption
        }
    }


// Usage:
showLoginActivityToken.launch(getLoginActivityTokenIntent(authorizationCode))
Run Code Online (Sandbox Code Playgroud)

请注意,该bearerWithToken参数应如下所示:"Bearer {your_access_token}"