如何在Android上实现OAuth2授权

8

我需要在我的应用程序中添加OAuth2授权。我只有客户端ID、客户端密钥和用户名(电子邮件)。我需要获取令牌。您可以给我一些如何实现的建议吗?库或示例代码?

1个回答

15

您可以使用AppAuth进行OAuth2授权。

请参阅https://github.com/openid/AppAuth-Android获取示例。


以下是AppAuth文档的简化版。

概述

建议原生应用程序使用授权码流程。

该流程实际上由四个阶段组成:

  1. 指定授权服务配置。
  2. 通过浏览器授权,以获取授权代码。
  3. 交换授权代码,以获取访问和刷新令牌。
  4. 使用访问令牌访问受保护的资源服务。

1. 创建授权服务配置

首先,创建一个授权服务的配置,该配置将在第二和第三阶段中使用。

AuthorizationServiceConfiguration mServiceConfiguration =
    new AuthorizationServiceConfiguration(
        Uri.parse("https://example.com/authorize"), // Authorization endpoint
        Uri.parse("https://example.com/token")); // Token endpoint

ClientAuthentication mClientAuthentication =
    new ClientSecretBasic("my-client-secret"); // Client secret

(不建议在原生应用中使用静态客户端密钥。)

2. 请求授权并获取授权码

为接收授权回调,在清单文件中定义以下活动。(您无需实现此活动,此活动将充当授权请求的代理。)

<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.example"/> <!-- Redirect URI scheme -->
    </intent-filter>
</activity>

构建并执行授权请求。

private void authorize() {
    AuthorizationRequest authRequest = new AuthorizationRequest.Builder(
        mServiceConfiguration,
        "my-client-id", // Client ID
        ResponseTypeValues.CODE,
        Uri.parse("com.example://oauth-callback") // Redirect URI
    ).build();

    AuthorizationService service = new AuthorizationService(this);

    Intent intent = service.getAuthorizationRequestIntent(authRequest);
    startActivityForResult(intent, REQUEST_CODE_AUTH);
}

处理授权响应。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode != REQUEST_CODE_AUTH) {
        return;
    }

    AuthorizationResponse authResponse = AuthorizationResponse.fromIntent(intent);
    AuthorizationException authException = AuthorizationException.fromIntent(intent);

    mAuthState = new AuthState(authResponse, authException);

    // Handle authorization response error here

    retrieveTokens(authResponse);
}

3. 交换授权码

private void retrieveTokens(AuthorizationResponse authResponse) {
    TokenRequest tokenRequest = response.createTokenExchangeRequest();

    AuthorizationService service = new AuthorizationService(this);

    service.performTokenRequest(request, mClientAuthentication,
            new AuthorizationService.TokenResponseCallback() {
        @Override
        public void onTokenRequestCompleted(TokenResponse tokenResponse,
                AuthorizationException tokenException) {
            mAuthState.update(tokenResponse, tokenException);

            // Handle token response error here

            persistAuthState(mAuthState);
        }
    });
}

在令牌检索成功后,持久化AuthState以便在下一次应用程序(重新)启动时重用它。

4. 访问受保护的资源服务

使用performActionWithFreshTokens使用新的访问令牌执行API调用。(它会自动确保令牌是最新的,并在需要时刷新它们。)

private void prepareApiCall() {
    AuthorizationService service = new AuthorizationService(this);

    mAuthState.performActionWithFreshTokens(service, mClientAuthentication,
            new AuthState.AuthStateAction() {
        @Override
        public void execute(String accessToken, String idToken,
                AuthorizationException authException) {
            // Handle token refresh error here

            executeApiCall(accessToken);
        }
    });
}

执行API调用。(AsyncTask仅为简便起见使用。它可能不是执行API调用的最佳解决方案。)

private void executeApiCall(String accessToken) {
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://example.com/api/...") // API URL
                    .addHeader("Authorization",
                            String.format("Bearer %s", params[0]))
                    .build();

            try {
                Response response = client.newCall(request).execute();
                return response.body().string();
            } catch (Exception e) {
                // Handle API error here
            }
        }

        @Override
        protected void onPostExecute(String response) {
            ...
        }
    }.execute(accessToken);
}

这是 Android 推荐的方法吗?我曾经认为移动设备可以使用设备的默认网络浏览器作为用户代理来处理代码和令牌重定向。最近有变化吗? - rj2700
2
Google 推荐使用 AppAuth。它使用 Chrome 自定义标签进行授权请求。与设备默认的 Web 浏览器相比,Chrome 自定义标签具有一些优势。例如,自定义标签会重叠上一个显示的活动。(请参见来自 Google 的以下讲话:https://youtu.be/DdQTXrk6YTk?t=220) - Matt Ke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接