Google OAuth2 for Android(type of web OAuth)

本文详细介绍如何在Android应用中集成Google OAuth2进行用户身份验证。包括创建项目、配置OAuth客户端、请求授权代码及实现授权流程等关键步骤,并提供代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Google OAuth2 for Android(type of web OAuth)

一、应用创建和注册

1.登录google

登录Google 应用
这里写图片描述

2.创建项目

这里写图片描述

3.创建OAuth同意屏幕

这里写图片描述

4.创建OAuth客户端

这里写图片描述
这里写图片描述

5.查看Google client id 和sercret key

这里写图片描述

二、Android app中如何使用OAuth客户端

1.配置和提交授权申请

使用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";

2.获取授权成功返回的accss token和refresh token

 // 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 认证完成。

三、参考文献

https://developers.google.com/identity/protocols/OAuth2

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值