gpt4 book ai didi

android - 用户从Android中的Gmail登录后如何获取访问 token ?

转载 作者:IT老高 更新时间:2023-10-28 22:16:34 28 4
gpt4 key购买 nike

我关注 Google Sign in for Android .现在我可以获得 idToken,但我之前使用的后端服务器期待 access Token,因为我之前使用的是 Google+ 登录。现在我不想改变我的服务器端。但是我仍然如何使用 Google 登录并在我的 android 应用程序中获取访问 token ,以便我可以验证我的用户到我的后端服务器。

我之前使用的是 GooglePlay Service 7.5.0,现在我使用的是最新的 GooglePlay Service 8.3.0。

最佳答案

根据您的要求,您可以使用以下代码:

首先,确保您有一个有效的 Web OAuth 2.0 客户端 ID:

<!-- Server Client ID.  This should be a valid Web OAuth 2.0 Client ID obtained
from https://console.developers.google.com/ -->
<string name="server_client_id">...e4p8.apps.googleusercontent.com</string>

然后在Activity类里面:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

...

// For sample only: make sure there is a valid server client ID.
validateServerClientID();

// [START configure_signin]
// Configure sign-in to request offline access to the user's ID, basic
// profile, and Google Drive. The first time you request a code you will
// be able to exchange it for an access token and refresh token, which
// you should store. In subsequent calls, the code will only result in
// an access token. By asking for profile access (through
// DEFAULT_SIGN_IN) you will also get an ID Token as a result of the
// code exchange.
String serverClientId = getString(R.string.server_client_id);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
.requestServerAuthCode(serverClientId)
.requestEmail()
.build();
// [END configure_signin]

// Build GoogleAPIClient with the Google Sign-In API and the above options.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}

private void getAuthCode() {
// Start the retrieval process for a server auth code. If requested, ask for a refresh
// token. Otherwise, only get an access token if a refresh token has been previously
// retrieved. Getting a new access token for an existing grant does not require
// user consent.
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_GET_AUTH_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == RC_GET_AUTH_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
Log.d(TAG, "onActivityResult:GET_AUTH_CODE:success:" + result.getStatus().isSuccess());

if (result.isSuccess()) {
// [START get_auth_code]
GoogleSignInAccount acct = result.getSignInAccount();
String authCode = acct.getServerAuthCode();

// Show signed-in UI.
mAuthCodeTextView.setText(getString(R.string.auth_code_fmt, authCode));
updateUI(true);

// TODO(user): send code to server and exchange for access/refresh/ID tokens.
// [END get_auth_code]
} else {
// Show signed-out UI.
updateUI(false);
}
}
}

你可以在下面的ServerAuthCodeActivity.java看到完整的代码

如果您使用该示例,结果将类似于以下屏幕截图:

BNK's screenshot

然后,您可以按照以下 Google 文档中提到的步骤(从步骤 #3 开始。使用 HTTPS POST 将身份验证代码发送到您的应用后端):

Google Sign-In for Android - Enabling Server-Side Access


更新:从评论中,如果您想直接从 android 客户端应用程序获取访问 token ,请使用以下示例代码(替换为您的 client_id、client_secret 和 auth 代码)

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormEncodingBuilder()
.add("grant_type", "authorization_code")
.add("client_id", "812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com")
.add("client_secret", "{clientSecret}")
.add("redirect_uri","")
.add("code", "4/4-GMMhmHCXhWEzkobqIHGG_EnNYYsAkukHspeYUk9E8")
.build();
final Request request = new Request.Builder()
.url("https://www.googleapis.com/oauth2/v4/token")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
Log.e(LOG_TAG, e.toString());
}

@Override
public void onResponse(Response response) throws IOException {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
final String message = jsonObject.toString(5);
Log.i(LOG_TAG, message);
} catch (JSONException e) {
e.printStackTrace();
}
}
});

请使用compile 'com.squareup.okhttp:okhttp:2.6.0'(ver 3-RC1会有不同的类)

响应成功后,您将在 logcat 中获得以下信息:

I/onResponse: {
"expires_in": 3600,
"token_type": "Bearer",
"refresh_token": "1\/xz1eb0XU3....nxoALEVQ",
"id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQxMWY1Ym......yWVsUA",
"access_token": "ya29.bQKKYah-........_tkt980_qAGIo9yeWEG4"
}

关于android - 用户从Android中的Gmail登录后如何获取访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33998335/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com