tesla授权过程
2023-01-05 本文已影响0人
钰大人
大致流程流程如下
- 通过webview加载获取返回的授权码(code).
- 通过code交换获取到access_token refresh_token expires_in等信息.
- 进而实现其他操作.
com.google.api-client:google-api-client:1.34.1
适用于 Java 的 Google OAuth 客户端库可与网络上的任何 OAuth 服务配合使用,而不仅仅是与 Google API 配合使用
1. 项目配置
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. 获取授权code的url
url=flow.newAuthorizationUrl().setRedirectUri(redirectUrl).setState(getRandomString(6)).build()
3.1 webview会进行cookie管理,且oauth中需要cookie才可执行。此处需要在webview开始前去掉所有缓存的cookies
cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookies(null); // 或根据url,自己处理.
cookieManager.setAcceptCookie(true);
4. 通过第三步返回的code执行交换
TokenResponse response = flow.newTokenRequest(code).setGrantType("authorization_code").setRedirectUri(redirectUrl).execute();
5. 搞定! God bless U