3 回答
要回答有关 oauth 范围的疑问(只是对 googlers 有用):
要完全理解,google-it 有一些关于身份验证和授权的概念。
检查用户/密码是否存在是关于身份验证部分。
授权部分需要范围:您被授权代表用户执行或接收的内容。要获取允许的范围列表,请查看 OAuth 服务文档。
从 Google 和 G+ 可以找到最常见的范围:https ://developers.google.com/+/api/oauth?hl=pt-ZA
例如,要从用户那里获取所有可能的信息,您可以使用范围:
“openid 个人资料电子邮件https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me ”
(第一个词指的是协议,后面是要求响应字段的词,所需的范围可以用空格分隔符一起声明)
注意:稍后,如果您尝试使用您的访问令牌来请求或执行您之前未使用范围请求的任何操作,该服务可能会返回授权错误。
对于 Google,您可以用来了解他的 OAuth 服务和范围的一个好工具是 OAuth Playground:https ://developers.google.com/oauthplayground/
你看过API 参考吗?
您可能正在寻找的课程是com.google.android.gms.auth.GoogleAuthUtil
.
除其他外,它提供了以下方法:
static String getToken(Context context, String accountName, String
说明:
对用户进行身份验证并返回有效的 Google 身份验证令牌,如果获取令牌时出错,则引发异常。
用法:
String token;
try {
token = GoogleAuthUtil.getToken(context, accountName, scope);
} catch (GooglePlayServicesAvailabilityException playEx) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
playEx.getConnectionStatusCode(),
Activity.this,
AUTH_REQUEST_CODE);
// Use the dialog to present to the user.
} catch (UserRecoverableAutException recoverableException) {
Intent recoveryIntent = recoverableException.getIntent();
// Use the intent in a custom dialog or just startActivityForResult.
} catch (GoogleAuthException authEx) {
// This is likely unrecoverable.
Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMesssage(), authEx);
} catch (IOException ioEx) {
Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
doExponentialBackoff();
}
您需要使用异步任务来获取它。
public void onConnected(Bundle connectionHint) {
// Reaching onConnected means we consider the user signed in.
Log.i(TAG, "onConnected");
// Update the user interface to reflect that the user is signed in.
mSignInButton.setEnabled(false);
mSignOutButton.setEnabled(true);
mRevokeButton.setEnabled(true);
// Retrieve some profile information to personalize our app for the user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
AsyncTask<Void, Void, String > task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String token = null;
final String SCOPES = "https://www.googleapis.com/auth/plus.login ";
try {
token = GoogleAuthUtil.getToken(
getApplicationContext(),
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:" + SCOPES);
} catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
return token;
}
@Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
System.out.print("email" + email);
mStatus.setText(String.format(
getResources().getString(R.string.signed_in_as),
currentUser.getDisplayName()));
Plus.PeopleApi.loadVisible(mGoogleApiClient, null)
.setResultCallback(this);
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT;
}
您的访问令牌将存储到令牌变量中。