谷歌的OAuth Webflow的Andr​​oid版 [英] Google OAuth Webflow Android

查看:96
本文介绍了谷歌的OAuth Webflow的Andr​​oid版的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能验证使用OAuth 2.0与谷歌的API?我已经使用本机对话流尝试,但最近与 GoogleAuthUtil 为gettoken()方法返回比一个不同的结果打破一周前。

How can you authenticate using OAuth 2.0 with Google APIs? I have tried using the native dialog flow but that recently broken with the GoogleAuthUtil getToken() method returning different results than a week ago.

https://gist.github.com/lawloretienne/7328878

是否有某种另类的像一个Webflow的做同样的事情?

Is there some kind of alternative like a webflow to do the same thing?

推荐答案

请确保在谷歌API来注册你的应用程序控制台

状态更改为开,这些API要访问。

Change the status to "On" for the APIs you wish to access.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <WebView android:id="@+id/webview"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
             android:layout_weight="1" />
</LinearLayout>

arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>  
    <string-array name="scopes">
        <item>https://www.google.com/m8/feeds</item>
        <item>https://www.googleapis.com/auth/userinfo.email</item>
        <item>https://www.googleapis.com/auth/plus.login</item>
        <item>https://www.googleapis.com/auth/userinfo.profile</item>
    </string-array>
</resources>

GoogleOAuthWebFlowActivity.java

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.biggu.shopsavvy.R;
import com.biggu.shopsavvy.utils.Toaster;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GoogleOAuthWebFlowActivity extends Activity {
    private WebView webview;
    private static final String TAG = "Main";
    private ProgressBar progressBar;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE | Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.google_oauth_webflow);

        this.webview = (WebView)findViewById(R.id.webview);

        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webview.addJavascriptInterface(new CustomJavaScriptInterface(), "Android");

        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

        setProgressBarIndeterminateVisibility(true);

        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "Processing webview url click...");
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url)  {
                Log.i(TAG, "Finished loading URL: " +url);
                setProgressBarIndeterminateVisibility(false);

                if(url.startsWith("https://accounts.google.com/o/oauth2/approval")){
                    String ht = "javascript:window.Android.retrieveExchangeCode(document.getElementsByTagName('title')[0].innerHTML);";
                    webview.loadUrl(ht);
                }
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.e(TAG, "Error: " + description);
                Toaster.makeToast("Oh no! " + description);
                alertDialog.setTitle("Error");
                alertDialog.setMessage(description);
                alertDialog.setButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                });
                alertDialog.show();
            }
        });

        String webLoginClientId = getString(R.string.client_client_id);
        String scope = TextUtils.join(" ", getResources().getStringArray(R.array.scopes));
        String redirect_uri = getString(R.string.client_redirect_uri);

        String url = "https://accounts.google.com/o/oauth2/auth?scope="+scope
                +"&client_id="+webLoginClientId
                +"&response_type=code&access_type=offline&approval_prompt=force&redirect_uri="+redirect_uri;

        webview.loadUrl(url);
    }

    private class CustomJavaScriptInterface {

        @JavascriptInterface
        public void retrieveExchangeCode(String titleTag) {

            String codePair = titleTag.substring(titleTag.indexOf("code="), titleTag.length());
            String codeValue = codePair.substring(5, codePair.length());

            Intent resultIntent = new Intent();
            resultIntent.putExtra("exchangeCode", codeValue);
            setResult(Activity.RESULT_OK, resultIntent);
            finish();
        }
    }
}

这篇关于谷歌的OAuth Webflow的Andr​​oid版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆