我需要在我的应用程序中添加OAuth2授权。我只有客户端ID、客户端密钥和用户名(电子邮件)。我需要获取令牌。您可以给我一些如何实现的建议吗?库或示例代码?
您可以使用AppAuth进行OAuth2授权。
请参阅https://github.com/openid/AppAuth-Android获取示例。
以下是AppAuth文档的简化版。
概述
建议原生应用程序使用授权码流程。
该流程实际上由四个阶段组成:
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);
}