Friday 18 March 2016

Android: Google+ and Facebook Login without SDK and libray

 Google+ Login

  • Create project at https://console.developers.google.com/

         and Get CLIENT_ID and CLIENT_SECRET

  • Create one class GetAccessToken.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class GetAccessToken {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public GetAccessToken() {
    }
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    Map<String, String> mapn;
    DefaultHttpClient httpClient;
    HttpPost httpPost;

    public JSONObject gettoken(String address,String token,String client_id,String client_secret,String redirect_uri,String grant_type) {
        // Making HTTP request
        try {
            // DefaultHttpClient
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(address);

            params.add(new BasicNameValuePair("code", token));
            params.add(new BasicNameValuePair("client_id", client_id));
            params.add(new BasicNameValuePair("client_secret", client_secret));
            params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
            params.add(new BasicNameValuePair("grant_type", grant_type));

            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            
            json = sb.toString();
            Log.e("JSONStr", json);
        } catch (Exception e) {
        e.getMessage();
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // Parse the String to a JSON Object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // Return JSON String
        return jObj;
    }
    
}


  • Now create Android activity to login at google+
package learn2crack.weboauth2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private static String CLIENT_ID = "2620035374-elvgrman1ltj8280ahbi027kff46gl8s.apps.googleusercontent.com";
// Use your own client id
private static String CLIENT_SECRET = "YDapcX77bFeMZSHd31P_sEhMsL";
// Use your own client secret
private static String REDIRECT_URI = "http://localhost";
private static String GRANT_TYPE = "authorization_code";
private static String TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
private static String OAUTH_URL = "https://accounts.google.com/o/oauth2/auth";
private static String OAUTH_SCOPE = "email%20profile";
// Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access = (TextView) findViewById(R.id.Access);
auth = (Button) findViewById(R.id.auth);
auth.setOnClickListener(new View.OnClickListener() {
Dialog auth_dialog;

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView) auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(OAUTH_URL + "?redirect_uri=" + REDIRECT_URI
+ "&response_type=code&client_id=" + CLIENT_ID
+ "&scope=" + OAUTH_SCOPE);
web.setWebViewClient(new WebViewClient() {

boolean authComplete = false;
Intent resultIntent = new Intent();

@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
super.onPageStarted(view, url, favicon);

}

String authCode;

@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

if (url.contains("?code=") && authComplete != true) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
Log.i("", "CODE : " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
MainActivity.this.setResult(Activity.RESULT_OK,
resultIntent);
setResult(Activity.RESULT_CANCELED, resultIntent);

SharedPreferences.Editor edit = pref.edit();
edit.putString("Code", authCode);
edit.commit();
auth_dialog.dismiss();
new TokenGet().execute();
Toast.makeText(getApplicationContext(),
"Authorization Code is: " + authCode,
Toast.LENGTH_SHORT).show();
} else if (url.contains("error=access_denied")) {
Log.i("", "ACCESS_DENIED_HERE");
resultIntent.putExtra("code", authCode);
authComplete = true;
setResult(Activity.RESULT_CANCELED, resultIntent);
Toast.makeText(getApplicationContext(),
"Error Occured", Toast.LENGTH_SHORT).show();

auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Learn2Crack");
auth_dialog.setCancelable(true);
}
});
}

private class TokenGet extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String Code;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Contacting Google ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
Code = pref.getString("Code", "");
pDialog.show();
}

@Override
protected JSONObject doInBackground(String... args) {
GetAccessToken jParser = new GetAccessToken();
JSONObject json = jParser.gettoken(TOKEN_URL, Code, CLIENT_ID,
CLIENT_SECRET, REDIRECT_URI, GRANT_TYPE);
return json;
}

@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if (json != null) {

try {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), json.toString(),
Toast.LENGTH_SHORT).show();
final String tok = json.getString("access_token");
String expire = json.getString("expires_in");
//String refresh = json.getString("refresh_token");
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
fetchNameFromProfileServer(tok);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
Log.d("Token Access", tok);
Log.d("Expire", expire);
//Log.d("Refresh", refresh);
auth.setText("Authenticated");
Access.setText("Access Token:" + tok + "\nExpires:"
+ expire + "\nRefresh Token:");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} else {
Toast.makeText(getApplicationContext(), "Network Error",
Toast.LENGTH_SHORT).show();
}
}
}

private void fetchNameFromProfileServer(String token) throws IOException,
JSONException {

URL url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int sc = con.getResponseCode();
Log.e("sc"+con.getResponseMessage(),""+sc);
if (sc == 200) {
InputStream is = con.getInputStream();
final String GOOGLE_USER_DATA = readResponse(is);
is.close();

runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, GOOGLE_USER_DATA, 1).show();
android.webkit.CookieManager.getInstance().removeAllCookie();
}
});
return;
} else if (sc == 401) {

return;
} else {

return;
}
}

private static String readResponse(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[2048];
int len = 0;
while ((len = is.read(data, 0, data.length)) >= 0) {
bos.write(data, 0, len);
}
return new String(bos.toByteArray(), "UTF-8");
}

}

--------------------------------------------------------------------------------------------------------------------------

Facebook Login

First create facebook app at https://developers.facebook.com/ for web platform

you will get AppID and App Secret automatically

Then set redirect url at Setting->advance Setting-> Redirect URL

Now Create  FBGraph.java and FBConnection.java following way

FBGraph.java..................................

ipackage com.example.root.testfacebook;
/*** Created by root on 7/3/16.*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

public class FBGraph {
private String accessToken;

public FBGraph(String accessToken) {
this.accessToken = accessToken;
}

public String getFBGraph() {
String graph = null;
try {

    String g = "https://graph.facebook.com/me?fields=id,name,email&" + accessToken;
    URL u = new URL(g);
    URLConnection c = u.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            c.getInputStream()));
    String inputLine;
    StringBuffer b = new StringBuffer();
    while ((inputLine = in.readLine()) != null)
        b.append(inputLine + "\n");
    in.close();
    graph = b.toString();
    System.out.println(graph);
} catch (Exception e) {
    e.printStackTrace();
    throw new RuntimeException("ERROR in getting FB graph data. " + e);
}
return graph;
}

public Map getGraphData(String fbGraph) {
Map fbProfile = new HashMap();
try {
    JSONObject json = new JSONObject(fbGraph);
    fbProfile.put("id", json.getString("id"));
    fbProfile.put("name", json.getString("name"));
    if (json.has("email"))
        fbProfile.put("email", json.getString("email"));
    if (json.has("gender"))
        fbProfile.put("gender", json.getString("gender"));
} catch (JSONException e) {
    e.printStackTrace();
    throw new RuntimeException("ERROR in parsing FB graph data. " + e);
}
return fbProfile;
}
}





FBConnection.java..........................................


package com.example.root.testfacebook;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class FBConnection {
    public static final String FB_APP_ID = "1509052649408092";
    public static final String FB_APP_SECRET = "3c19b5928afaa0121241f964ce37b4c9";
    public static final String REDIRECT_URI = "http://192.168.168.24/xampp/index.php";


    static String accessToken = "";

    public String getFBAuthUrl() {
        String fbLoginUrl = "";
        try {
            fbLoginUrl = "http://www.facebook.com/dialog/oauth?" + "client_id="                    + FBConnection.FB_APP_ID + "&redirect_uri="                    + URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
                    + "&scope=email";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fbLoginUrl;
    }

    public String getFBGraphUrl(String code) {
        String fbGraphUrl = "";
        try {
            fbGraphUrl = "https://graph.facebook.com/oauth/access_token?"                    + "client_id=" + FBConnection.FB_APP_ID + "&redirect_uri="                    + URLEncoder.encode(FBConnection.REDIRECT_URI, "UTF-8")
                    + "&client_secret=" + FB_APP_SECRET + "&code=" + code;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fbGraphUrl;
    }

    public String getAccessToken(String code) {
        if ("".equals(accessToken)) {
            URL fbGraphURL;
            try {
                fbGraphURL = new URL(getFBGraphUrl(code));
            } catch (MalformedURLException e) {
                e.printStackTrace();
                throw new RuntimeException("Invalid code received " + e);
            }
            URLConnection fbConnection;
            StringBuffer b = null;
            try {
                fbConnection = fbGraphURL.openConnection();
                BufferedReader in;
                in = new BufferedReader(new InputStreamReader(
                        fbConnection.getInputStream()));
                String inputLine;
                b = new StringBuffer();
                while ((inputLine = in.readLine()) != null)
                    b.append(inputLine + "\n");
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Unable to connect with Facebook "+ e);
            }

            accessToken = b.toString();
            if (accessToken.startsWith("{")) {
                throw new RuntimeException("ERROR: Access Token Invalid: "+ accessToken);
            }
        }
        return accessToken;
    }
}
Now create activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/webview_frame"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#0099cc"
 tools:context=".MyActivity">
 <ProgressBar
 android:id="@+id/progressBar"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center" />
 <WebView
 android:id="@+id/webview"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</FrameLayout>



Java class


package com.example.root.testfacebook;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaActionSound;
import android.net.Uri;

import android.net.UrlQuerySanitizer;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.Map;

public class MainActivity extends AppCompatActivity {
protected WebView mainWebView;
private ProgressBar mProgress;
private Context mContext;
private WebView mWebviewPop;
private FrameLayout mContainer;

FBConnection fbConnection;

@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fbConnection = new FBConnection();
String url = fbConnection.getFBAuthUrl();

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

//Progress BarmProgress = (ProgressBar) findViewById(R.id.progressBar);

//Cookie manager for the webviewCookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);


mContainer = (FrameLayout) findViewById(R.id.webview_frame);

//SettingsWebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);

mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);

mainWebView.setWebChromeClient(new MyCustomChromeClient());
mainWebView.loadUrl(url);

mContext = this.getApplicationContext();


}


private class MyCustomWebViewClient extends WebViewClient {
@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {
    String host = Uri.parse(url).getHost();


    if (host.equals("m.facebook.com") || host.equals("www.facebook.com")) {
        return false;
    }

    if (url.contains("code")) {
        final Uri uri = Uri.parse(url);


        new Thread(new Runnable() {
            @Override            public void run() {

                String accessToken = fbConnection.getAccessToken(uri.getQueryParameter("code"));

                FBGraph fbGraph = new FBGraph(accessToken);
                String graph = fbGraph.getFBGraph();
                final Map<String, String> fbProfileData = fbGraph.getGraphData(graph);
                runOnUiThread(new Runnable() {
                    @Override                    public void run() {
                        Toast.makeText(MainActivity.this, fbProfileData.get("email").toString(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    view.loadUrl(url);

    return true;
}

@Overridepublic void onReceivedSslError(WebView view, SslErrorHandler handler,
                               SslError error) {

}

}

private class MyCustomChromeClient extends WebChromeClient {

@Overridepublic boolean onCreateWindow(WebView view, boolean isDialog,
                              boolean isUserGesture, Message resultMsg) {
    mWebviewPop = new WebView(mContext);
    mWebviewPop.setVerticalScrollBarEnabled(false);
    mWebviewPop.setHorizontalScrollBarEnabled(false);
    mWebviewPop.setWebViewClient(new MyCustomWebViewClient());
    mWebviewPop.getSettings().setJavaScriptEnabled(true);
    mWebviewPop.getSettings().setSavePassword(false);
    mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams
   (ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    mContainer.addView(mWebviewPop);
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(mWebviewPop);
    resultMsg.sendToTarget();

    return true;
}

@Overridepublic void onCloseWindow(WebView window) {

}

}

}