You need to enable JavaScript to run this app. Android OAuth2 AppAuth 库 Kotlin 使用示例求助
优惠活动
大模型
产品
解决方案
定价
更多

Android OAuth2 AppAuth 库 Kotlin 使用示例求助

AppAuth for Android Kotlin 完整使用示例

1. 项目依赖配置

在模块级build.gradle文件中添加依赖和编译配置:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    // 配置重定向Scheme,替换为你自己的重定向Scheme
    manifestPlaceholders = [
        'appAuthRedirectScheme': 'com.yourapp.package'
    ]
}

dependencies {
    // AppAuth核心依赖
    implementation 'net.openid:appauth:0.11.1'
    // 可选:用于JSON解析
    implementation 'com.google.code.gson:gson:2.10.1'
}

2. AndroidManifest 配置

添加AppAuth所需的组件声明和权限配置:

<!-- Android 11+ 查询可用浏览器所需 -->
<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
</queries>

<application ...>
    <!-- AppAuth 重定向接收组件 -->
    <activity
        android:name="net.openid.appauth.RedirectUriReceiverActivity"
        android:exported="true">
        <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="${appAuthRedirectScheme}" />
        </intent-filter>
    </activity>
</application>

3. 核心功能实现

3.1 常量配置

先定义你自己的OAuth服务参数:

// 替换为你自己的授权服务配置
private const val AUTH_ENDPOINT = "https://your-auth-server.com/oauth2/auth"
private const val TOKEN_ENDPOINT = "https://your-auth-server.com/oauth2/token"
private const val CLIENT_ID = "your-client-id"
private const val REDIRECT_URI = "com.yourapp.package:/oauth2callback"
private const val SCOPE = "openid profile email"

3.2 初始化授权服务和回调

在Activity/Fragment中初始化相关组件:

class OAuthActivity : AppCompatActivity() {
    private lateinit var authService: AuthorizationService
    private var authState: AuthState = AuthState()

    // 授权回调注册
    private val authLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            val data = result.data ?: return@registerForActivityResult
            val response = AuthorizationResponse.fromIntent(data)
            val error = AuthorizationException.fromIntent(data)

            authState.update(response, error)
            response?.let {
                exchangeToken(it)
            } ?: run {
                // 处理授权错误
                Log.e("AppAuth", "授权失败: ${error?.message}")
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        authService = AuthorizationService(this)
    }

3.3 发起授权请求

private fun launchAuthorization() {
    val serviceConfig = AuthorizationServiceConfiguration(
        Uri.parse(AUTH_ENDPOINT),
        Uri.parse(TOKEN_ENDPOINT)
    )

    val authRequest = AuthorizationRequest.Builder(
        serviceConfig,
        CLIENT_ID,
        ResponseTypeValues.CODE,
        Uri.parse(REDIRECT_URI)
    ).setScope(SCOPE)
     .build()

    val authIntent = authService.getAuthorizationRequestIntent(authRequest)
    authLauncher.launch(authIntent)
}

3.4 授权码交换Token

private fun exchangeToken(authResponse: AuthorizationResponse) {
    val tokenRequest = authResponse.createTokenExchangeRequest()
    authService.performTokenRequest(tokenRequest) { tokenResponse, exception ->
        authState.update(tokenResponse, exception)
        tokenResponse?.let {
            val accessToken = it.accessToken
            val refreshToken = it.refreshToken
            val idToken = it.idToken
            // 存储Token信息到本地
            Log.d("AppAuth", "获取Token成功: $accessToken")
        } ?: run {
            Log.e("AppAuth", "交换Token失败: ${exception?.message}")
        }
    }
}

3.5 刷新AccessToken示例

private fun refreshAccessToken() {
    authState.refreshToken?.let { refreshToken ->
        val tokenRequest = TokenRequest.Builder(
            authState.authorizationServiceConfiguration!!,
            CLIENT_ID
        ).setGrantType(GrantTypeValues.REFRESH_TOKEN)
         .setRefreshToken(refreshToken)
         .build()

        authService.performTokenRequest(tokenRequest) { tokenResponse, exception ->
            authState.update(tokenResponse, exception)
            tokenResponse?.let {
                Log.d("AppAuth", "刷新Token成功: ${it.accessToken}")
            }
        }
    }
}

3.6 携带AccessToken请求业务接口示例

private fun requestUserInfo() {
    authState.accessToken?.let { accessToken ->
        // 示例用OkHttp请求,可替换为你自己的网络请求库
        val request = Request.Builder()
            .url("https://your-api-server.com/user/info")
            .addHeader("Authorization", "Bearer $accessToken")
            .build()

        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 处理请求失败
            }

            override fun onResponse(call: Call, response: Response) {
                // 处理返回的用户信息
            }
        })
    }
}

4. 注意事项

  • AppAuth默认开启PKCE授权流,无需在客户端存储client secret,符合公共客户端安全规范
  • 配置的REDIRECT_URI必须和授权服务端注册的完全一致,否则会回调失败
  • 使用完AuthorizationService后需要在onDestroy中关闭资源:
override fun onDestroy() {
    super.onDestroy()
    authService.dispose()
}

内容的提问来源于stack exchange,提问作者amir215909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 10:06:04