Thursday 1 December 2016

Integrating Google+ Social media login with your webpage/website

Elopade.com has a new google+ social media login.

Discussing elopade.com code will be lengthy, so i have come with a simulating  google+ integration with jsp & servlet demo example.

so here we go..

project structure:



web.xml
-------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>socialMediaLogin</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

index.jsp
-------------------------------------

<!DOCTYPE html>
<%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
if (session.getAttribute("username") == null) {
%>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>

<form action="LoginServlet" method="post">
UserName: <input type="text" name="user" id = "user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">

<a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://localhost:8080/aSession/oauth2callback&response_type=code&client_id=54353647045-1bj3evf69hq0eop496o5k7lktk1p6rpu.apps.googleusercontent.com&approval_prompt=force">Login With Gmail</a>

</form>
</body>
</html>
<%
} else {
response.sendRedirect("LoginSuccess.jsp");
}
%>


GooglePojo.java
------------------------------------

package com.session;


public class GooglePojo
{
  String id;
  String email;
  boolean verified_email;
  String name;
  String given_name;
  String family_name;

  public String getId()
  {
    return this.id;
  }

  public void setId(String id)
  {
    this.id = id;
  }

  public String getEmail()
  {
    return this.email;
  }

  public void setEmail(String email)
  {
    this.email = email;
  }

  public boolean isVerified_email()
  {
    return this.verified_email;
  }

  public void setVerified_email(boolean verified_email)
  {
    this.verified_email = verified_email;
  }

  public String getName()
  {
    return this.name;
  }

  public void setName(String name)
  {
    this.name = name;
  }

  public String getGiven_name()
  {
    return this.given_name;
  }

  public void setGiven_name(String given_name)
  {
    this.given_name = given_name;
  }

  public String getFamily_name()
  {
    return this.family_name;
  }

  public void setFamily_name(String family_name)
  {
    this.family_name = family_name;
  }

  public String toString()
  {
    return
 
      "GooglePojo [id=" + this.id + ", email=" + this.email + ", verified_email=" + this.verified_email + ", name=" + this.name + ", given_name=" + this.given_name + ", family_name=" + this.family_name + "]";
  }
}


GsonUtility.java
----------------------------------

package com.session;


import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class GsonUtility
{
  static Gson gson = new Gson();
  
  public static String tojson(Object object)
  {
    return gson.toJson(object);
  }
  
  public static String getFbAccessTokenFromJson(String j)
  {
    JsonObject json = (JsonObject)new JsonParser().parse(j);
    JsonObject authr = (JsonObject)json.get("authResponse");
    String act = authr.get("access_token").getAsString();
    return act;
  }
  
  public static String getJsonElementString(String name, String gs)
  {
    try
    {
      JsonObject json = (JsonObject)new JsonParser().parse(gs);
      return json.get(name).getAsString();
    }
    catch (Exception localException) {}
    return null;
  }
  

  public static String getElementString(String string, String line1)
  {
    if (line1.indexOf(string) != -1)
    {
      int k = string.length();
      return line1.substring(k + 1, line1.indexOf("&"));
    }
    return line1;
  }
}


LoginServlet.java
--------------------------------------

package com.session;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "uid";
private final String password = "pwd";

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");

if (userID.equals(user) && password.equals(pwd)) {
HttpSession session = request.getSession(true);
session.setAttribute("username", user);
response.sendRedirect("LoginSuccess.jsp");
} else {
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}

}

}


OAuth2Callback.java
----------------------------------------------------

package com.session;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/oauth2callback")
public class OAuth2Callback extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
try
{
String code = request.getParameter("code");
System.out.println(code);
String urlParameters = "code=" +
code +
"&client_id=" + Setup.CLIENT_ID +
"&client_secret=" + Setup.CLIENT_SECRET +
"&redirect_uri=" + Setup.REDIRECT_URL +
"&grant_type=authorization_code";
System.out.println(urlParameters);
URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line1 = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
line1 = line1 + line;
}
String s = GsonUtility.getJsonElementString("access_token", line1);
url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token=" +
s);
conn = url.openConnection();
line1 = "";
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = reader.readLine()) != null) {
line1 = line1 + line;
}
GooglePojo data = (GooglePojo) new Gson().fromJson(line1, GooglePojo.class);
writer.close();
reader.close();
request.setAttribute("auth", data);
session.setAttribute("username", data.getName());
request.getRequestDispatcher("/LoginSuccess.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}



Setup.java
----------------------------------------

package com.session;


public class Setup {
  public static final String CLIENT_ID = "545876977045-1bj3eerere0eop496o5k7lktk1p6rpu.apps.googleusercontent.com";
  public static final String CLIENT_SECRET = "LRdeGc8kerreroUBtS2Oy83";
  public static final String REDIRECT_URL = "http://localhost:8080/aSession/oauth2callback";
}


LoginSuccess.jsp
------------------------------------------

<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
int one = 1;
if ( one == 1) {
// String username = request.getAttribute("username").toString(); 
/* session.getAttribute("username") != null && !session.getAttribute("username").toString().trim().isEmpty() */
%>
<%@page import="com.session.GooglePojo"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
blahs
</body>
</html>
<%
} else {
response.sendRedirect("index.jsp");
}
%>

LogoutSuccess.jsp
--------------------------------------------

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
if (session.getAttribute("username") != null && !session.getAttribute("username").toString().trim().isEmpty()) {
String username = session.getAttribute("username").toString();
session.invalidate();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
User <%=username%> Have been Logged Out Successfully.

<br/><a href="index.jsp"><input type="button" value="Login"></a>

</body>
</html>
<%
} else {
response.sendRedirect("index.jsp");
}
%>

welcome2.jsp
------------------------------

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%
if (session.getAttribute("username") != null && !session.getAttribute("username").toString().trim().isEmpty()) {
String username = session.getAttribute("username").toString();
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>welcome 2</title>
</head>
<body>
<h3>Hi <%=username %>, Login successful.</h3>
<br>
<a href="LogoutSuccess.jsp"><input type="button" value="Logout"></a>
<footer>
</footer>
</body>
</html>
<%
} else {
response.sendRedirect("index.jsp");
}
%>


Please note: I have not given my real client id or secre key for this demo. You will have to generate your own secret key and client id for the URL you need to integrate with social media.

You can see how this functionality works with mu current website:elopade.com

No comments:

Post a Comment