大致流程流程如下
- 通過(guò)webview加載獲取返回的授權(quán)碼(code).
- 通過(guò)code交換獲取到access_token refresh_token expires_in等信息.
- 進(jìn)而實(shí)現(xiàn)其他操作.
com.google.api-client:google-api-client:1.34.1
適用于 Java 的 Google OAuth 客戶端庫(kù)可與網(wǎng)絡(luò)上的任何 OAuth 服務(wù)配合使用,而不僅僅是與 Google API 配合使用
1. 項(xiàng)目配置
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.api-client:google-api-client:1.32.1'
}
2. 配置
private static final String CLIENT_ID = "ownerapi";
private static final String CLIENT_SECRET = "c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3";
AuthorizationCodeFlow.Builder builder = new AuthorizationCodeFlow.Builder(
BearerToken.authorizationHeaderAccessMethod(),
new NetHttpTransport(),
new GsonFactory(),
new GenericUrl(tokenUrl),
new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET),
CLIENT_ID,
authUrl
).setScopes(Arrays.asList("openid", "email", "offline_access")).enablePKCE();
flow = builder.build();
3. 獲取授權(quán)code的url
url=flow.newAuthorizationUrl().setRedirectUri(redirectUrl).setState(getRandomString(6)).build()
3.1 webview會(huì)進(jìn)行cookie管理,且oauth中需要cookie才可執(zhí)行。此處需要在webview開(kāi)始前去掉所有緩存的cookies
cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookies(null); // 或根據(jù)url,自己處理.
cookieManager.setAcceptCookie(true);
4. 通過(guò)第三步返回的code執(zhí)行交換
TokenResponse response = flow.newTokenRequest(code).setGrantType("authorization_code").setRedirectUri(redirectUrl).execute();
5. 搞定! God bless U