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

Session Management JSP

Managing sessions is a crucial task while creating your website/ web application.

That being said, let's see how to manage sessions based on validity of logged in user id.

What we want is that after successful login, user cannot navigate back to index page until logged out or until session expires. Once once logged out, user cannot navigate to transactional pages.

Here's a simulation program for that. Get the logic from this small flow and you can implement it in any big program.

Here we go..

Project Structure:


                               

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

<web-app id="WebApp_ID" version="2.4"
   xmlns="http://java.sun.com/xml/ns/j2ee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Spring MVC Application</display-name>

   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

HelloWeb-servlet.xml
-----------------------------------------
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:component-scan base-package="com.user" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

UserPojo.java
----------------------------------------------------------

package com.user;

import java.io.Serializable;

public class UserPojo implements Serializable {

private static final long serialVersionUID = 1L;
private String username;
private String password;
public UserPojo() {}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}


HelloController.java
------------------------------------------------------------

package com.user;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.security.web.util.RedirectUrlBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

@Controller
@RequestMapping("/")
public class HelloController {
private final String userID = "uid";
private final String password = "pwd";
@RequestMapping(method = RequestMethod.GET)
public ModelAndView login(HttpSession session) {
if(session.getAttribute("username")==null) {
ModelAndView model = new ModelAndView("login");
model.addObject("message", "JSP page Session Demo.");
return model;
} else {
ModelAndView model = new ModelAndView("LoginSuccess");
model.addObject("message", "Welcome, User "+session.getAttribute("username").toString()+" login successfully.");
return model;
}
}

@RequestMapping(value = "checkLogin", method = RequestMethod.POST)
public String checkLogin(HttpSession session, UserPojo user,RedirectUrlBuilder redirect) {
if (user.getUsername().equalsIgnoreCase(userID) && user.getPassword().equalsIgnoreCase(password)) {
   session.setAttribute("username",user.getUsername());
return "redirect:/LoginSuccess";
} else {
return "redirect:";
}
}
@RequestMapping(value = "LoginSuccess", method = RequestMethod.GET)
public ModelAndView welcomePage(HttpSession session, UserPojo user,RedirectUrlBuilder redirect) {
ModelAndView model = new ModelAndView("LoginSuccess");
model.addObject("message", "Welcome to JSP page Session Demo.");
return model;
}
@RequestMapping(value = "logout", method = RequestMethod.GET)
public ModelAndView logoutSession(HttpSession session) {
String username = "";
if(session.getAttribute("username")!=null) {
username = session.getAttribute("username").toString();
session.invalidate(); 
}
ModelAndView model = new ModelAndView("login");
model.addObject("message", "Welcome Spring Login Demo.");
model.addObject("logout", "User "+username+" logout successfully.");
return model;
}
@RequestMapping(value = "welcome", method = RequestMethod.GET)
public ModelAndView welcomePage(HttpSession session) {
ModelAndView model = new ModelAndView("welcome2");
model.addObject("message", "JSP page Session Demo - page 2.");
model.addObject("username", session.getAttribute("username"));
return model;
}
    
}


login.jsp
------------------------------------------------------------

<%@ page contentType="text/html; charset=UTF-8" %>
<% 
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");
%>
<html>
<head>
<title>Login Page</title>
</head>
<body>
   <h2>${message}</h2>
   <form action="checkLogin" method="post">
  UserName : <input type="text" name="username"><br/>
  Password : <input type="password" name="password"><br/>
  <input type="submit" name="login" value="Login">
   </form>

<h2>${logout}</h2>
</body>
</html>

LoginSuccess.jsp
-----------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% 
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()) {
%>
<!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>
<c:out value="${message}" /><br/>

<a href="welcome"><input type="button" value="welcome2"></a>
<a href="logout"><input type="button" value="Logout"></a>
</body>
</html>
<%
} else {
response.sendRedirect("");
}
%>

welcome2.java
------------------------------------

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% 
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()) {
%>    
<!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="logout"><input type="button" value="Logout"></a>
<footer>
</footer>
</body>
</html>
<%
} else {
response.sendRedirect("");
}
%>

Now deploy and run the program
-----------------------------------------------------------------------

welcome page
--------------------

uid: uid
password: pwd

on successful login:


on clicking back button from this page, it is redirected to this page (LoginSuccess page) itself and back navigation is blocked to welcome page.

On clicking logout, you will be redirected to logout page and you would not be able to navigate back to LoginSuccess page: