如何在Android应用程序中使用OAuth登录到Gmail?[英] How to Login into Gmail using OAuth in Android Application?

本文是小编为大家收集整理的关于如何在Android应用程序中使用OAuth登录到Gmail?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在开发一个应用程序,该应用程序使用登录到gmail.i进行了所有教程,在OAuth 2.0下标记的stackoverflow问题以及在Google中可用的文档,最后根据Google官方文件中提供的指南, OAuth 2.0 sample .我创建了客户ID以及安装应用程序所需的所有内容,即为Android.现在一切都很好,我打电话给用户的许可,之后我在WebView中得到了Accesstoken,然后说4/cR7XXXXXXXXXXXXXXX,然后说Please copy this code,switch to your application and paste it here.我很困惑,我在这里,我不知道该怎么办,要从Webview .AM返回我的应用程序大约两天,但是我无法为我的问题获得好的答案.在这里,我被停止了.

Main.java用户有OptionMenu登录.当用户单击WebView打开以输入Gmail时.

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {
    public static String REQUEST = "https://accounts.google.com/o/oauth2/auth?"
            + "client_id=XXXXXXXXXXX-gxxxx.apps.googleusercontent.com&"
            + "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
            + "scope=https://mail.google.com/mail/feed/atom&"
            + "response_type=code&" + "access_type=online";

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

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case 0:
            if (requestCode != RESULT_OK || data == null) {
                return;
            }
            String token = data.getStringExtra("token");
            if (token != null) {

            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.item1:
            Intent intent_obj2 = new Intent(Main.this, Webview.class);
            intent_obj2.setData(Uri.parse(REQUEST));
            startActivityForResult(intent_obj2, 0);
            return true;
            }
        return super.onOptionsItemSelected(item);
    }
}

webview.java

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Webview extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        final WebView wb_obj = new WebView(this);
        setContentView(wb_obj);
        wb_obj.getSettings().setJavaScriptEnabled(true);
        Intent intent = getIntent();
        if (intent.getData() != null) {
            wb_obj.loadUrl(intent.getDataString());
        }

        wb_obj.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setProgress(newProgress * 10000);
            }

        });
        wb_obj.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                setTitle(url);
                System.out.println(url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("in onPageFinsihed");

                /*CookieSyncManager.getInstance().sync();
                String s_cookie = CookieManager.getInstance().getCookie(url);
                if (s_cookie == null) {
                    System.out.println(s_cookie);
                    return;
                }else{

                String web_title = wb_obj.getTitle().toString();
                System.out.println("web tile" + web_title);

                if (web_title.equalsIgnoreCase("Request for Permission")) {

                } else {

                    String[] s_webtitle = web_title.split("=", 2);
                    String access_token = s_webtitle[1].toString();
                    //System.out.println("Access token" + access_token);
                    startActivity(new Intent(Webview.this, Main.class));
                    finish();
                }*/
                }

        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(Webview.this, Main.class));
    }
}

根据webview.java我打电话finish(),以便当前的活动被杀死,但这是在此应用中发生的,这样我就可以在onAcitivityResult()中获得令牌.请分享您的答案,谢谢.

.

推荐答案

以下步骤需要登录到Google.

1- 使用以下代码从设备中选择一个帐户

public static AccountManager accountManager;
accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");

2 - 使用以下代码从选定的帐户获取令牌

private void onAccountSelected(final Account account) {
accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
    try {
        String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
        useToken(account, token);
    } catch (OperationCanceledException e) {
        onAccessDenied();
    } catch (Exception e) {
        handleException(e);
    }
}
}, null);

}

3 - 现在使用用户帐户和令牌对令牌进行身份验证.您将能够登录到Google.

注意: 您将获得身份验证的完整代码身份验证代码,将您的gmail a/c和令牌放在需要的情况下.现在您可以使用Oauth弹跳.

4- 重新登录,您必须使用以下代码

将令牌无效
accountManager.invalidateAuthToken("com.google", token);

5- 无效后,您必须使用以下代码

获得新的令牌
 String newToken = AccountManager.get(this).getAuthToken(new Account(account,        "com.google"),
             AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);

6- 在您的androidmanifest.xml中添加以下使用权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>

那就是您所需要的,现在享受.

其他推荐答案

考虑使用" localhost:port"作为重定向uri而不是urn:ietf:wg:wg:oauth:2.0:oob&(有关更多详细信息,请参阅 https://develovelers.google.com/youtube/v3/guides/guides/authentication#installed-apps )和捕获这个url在回调中加载在WebView中: public boolean shopsoverrideurlloalloading(WebView视图,字符串URL).

其他推荐答案

对于使用OAuth2令牌访问Gmail API的另一种方法,您可以考虑此帖子的答案: oauth and java(连接到gmail).

本文地址:https://www.itbaoku.cn/post/102561.html

问题描述

I am Developing an application which uses Login to Gmail.I gone through all tutorials,stackoverflow questions which is tagged under OAuth 2.0 and documents that are available in google and finally as per the guide lines given in official document of Google for OAuth 2.0 sample. I have created Client ID and everything that is required for installed applications i.e., for Android. Everything up to now works fine,and i called WebView to grant permission from the user,After that i got Accesstoken like 4/cR7XXXXXXXXXXXXXXX in the WebViewand saying something like Please copy this code,switch to your application and paste it here.I am confused here,i don't know what to do,to get back to my app from Webview .Am searching for the solution about two days but,Am not able to get good answer for my problem.Here is the code where i was got stoped.

Main.java where user have an OptionMenu to login. When the user clicks WebViewopens to enter gmail.

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {
    public static String REQUEST = "https://accounts.google.com/o/oauth2/auth?"
            + "client_id=XXXXXXXXXXX-gxxxx.apps.googleusercontent.com&"
            + "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
            + "scope=https://mail.google.com/mail/feed/atom&"
            + "response_type=code&" + "access_type=online";

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

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case 0:
            if (requestCode != RESULT_OK || data == null) {
                return;
            }
            String token = data.getStringExtra("token");
            if (token != null) {

            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.item1:
            Intent intent_obj2 = new Intent(Main.this, Webview.class);
            intent_obj2.setData(Uri.parse(REQUEST));
            startActivityForResult(intent_obj2, 0);
            return true;
            }
        return super.onOptionsItemSelected(item);
    }
}

Webview.java

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Webview extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        final WebView wb_obj = new WebView(this);
        setContentView(wb_obj);
        wb_obj.getSettings().setJavaScriptEnabled(true);
        Intent intent = getIntent();
        if (intent.getData() != null) {
            wb_obj.loadUrl(intent.getDataString());
        }

        wb_obj.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setProgress(newProgress * 10000);
            }

        });
        wb_obj.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                setTitle(url);
                System.out.println(url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("in onPageFinsihed");

                /*CookieSyncManager.getInstance().sync();
                String s_cookie = CookieManager.getInstance().getCookie(url);
                if (s_cookie == null) {
                    System.out.println(s_cookie);
                    return;
                }else{

                String web_title = wb_obj.getTitle().toString();
                System.out.println("web tile" + web_title);

                if (web_title.equalsIgnoreCase("Request for Permission")) {

                } else {

                    String[] s_webtitle = web_title.split("=", 2);
                    String access_token = s_webtitle[1].toString();
                    //System.out.println("Access token" + access_token);
                    startActivity(new Intent(Webview.this, Main.class));
                    finish();
                }*/
                }

        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(Webview.this, Main.class));
    }
}

As per Webview.java i called finish() so that current activity gets killed but this is nit happening in this app,so that i will get token in onAcitivityResult().Please share Your answers thank you.

推荐答案

Below steps are require to login to Google.

1- Select an account from your device using below code

public static AccountManager accountManager;
accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");

2- Get a Token from selected account using below code

private void onAccountSelected(final Account account) {
accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, this, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
    try {
        String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
        useToken(account, token);
    } catch (OperationCanceledException e) {
        onAccessDenied();
    } catch (Exception e) {
        handleException(e);
    }
}
}, null);

}

3- now Authenticate the Token using user account and Token. you will be able to login to google.

NOTE: you will get Authentication full code from here Authentication code , put your gmail a/c and token where required. now you are able to loging using OAuth.

4- for re login you have to invalidate your token using below code

accountManager.invalidateAuthToken("com.google", token);

5- after invalidate you have to get a new token using below code

 String newToken = AccountManager.get(this).getAuthToken(new Account(account,        "com.google"),
             AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);

6- in your AndroidManifest.xml add below uses permissions

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>

Thats all you require, now enjoy.

其他推荐答案

Consider using "localhost:port" as the redirect uri instead of urn:ietf:wg:oauth:2.0:oob& (for more details refer to https://developers.google.com/youtube/v3/guides/authentication#installed-apps) and trap this URL being loaded in the webview in the callback: public boolean shouldOverrideUrlLoading (WebView view, String url).

其他推荐答案

For an alternative way of accessing the Gmail API with an OAuth2 token, you may consider the answers from this post: OAuth and Java (connecting to GMail).