使用Github第三方的libAndroidOAuth
请求Google授权代码如下:
public void googleLogin(View v) { GoogleOAuth.login(this) .setClientId(Credentials.GOOGLE_CLIENT_ID) .setClientSecret(Credentials.GOOGLE_CLIENT_SECRET) .setAdditionalScopes("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/youtube") .setRedirectUri(Credentials.GOOGLE_REDIRECT_URI) .setCallback(new OnLoginCallback() { @Override public void onSuccess(String token, SocialUser user) { afterLogin(token, user); } @Override public void onError(Exception error) { error.printStackTrace(); } }) .init(); }
- GOOGLE_CLIENT_ID:前文创建应用生成的client id;
- GOOGLE_CLIENT_SECRET:前文创建应用生成的secret key;
- Scopes:https://www.googleapis.com/auth/plus.login为认证服务器地址(必填);后面两个网址为申请的授权权限(可根据需求自定义):如读取生日和使用youtube api相关权限;
-RedirectUri:完成授权后的重定向uri
上述方式可以获取access token,但是可能获取不到refresh token,这时候需要重写init();
将final String authUrl = service.getAuthorizationUrl();
修改为final String authUrl = service.getAuthorizationUrl()+"&access_type=offline";
// Generating a complex state for better security // http://twobotechnologies.com/blog/2014/02/importance-of-state-in-oauth2.html public void init() { final String state = UUID.randomUUID().toString(); final OAuth20Service service = new ServiceBuilder().apiKey( clientId ).apiSecret( clientSecret ).callback( redirectUri ).state( state ).scope( scopes ).build( oAuth.api ); final String authUrl = service.getAuthorizationUrl() + "&access_type=offline"; Log.d( "1111", "-----authUrl=" + authUrl ); ConsentDialog.newInstance( authUrl, state ).setOnGetCodeCallback( new OnGetCodeCallback() { @Override public void onSuccess(final String code) { AsyncTask.execute( new Runnable() { @Override public void run() { try { final OAuth2AccessToken accessToken = service.getAccessToken( code ); final SocialUser account = oAuth.getAccount( service, accessToken ); oAuth.activity.runOnUiThread( new Runnable() { @Override public void run() { Log.d( "1111", "accessToken.getRefreshToken() =" + accessToken.getRefreshToken() ); callback.onSuccess( accessToken.getAccessToken(), account ); Log.d( "1111", "accessToken.getRefreshToken() =" + accessToken.getRefreshToken() ); } } ); } catch (final Exception e) { oAuth.activity.runOnUiThread( new Runnable() { @Override public void run() { callback.onError( e ); } } ); } } } ); } @Override public void onError(Exception error) { callback.onError( error ); } } ).show( oAuth.activity.getFragmentManager(), ConsentDialog.class.getName() ); } }
注意回调onSuccess是成功,onError是失败。通过accessToken 可以获取accessToken.getAccessToken()和accessToken.getRefreshToken()。
至此,Google OAuth 认证完成。
联系客服