Code ví dụ JSP Servlet login bằng Google (Gmail/Google+)

Code ví dụ JSP Servlet login bằng Google (Gmail/Google+)

(Xem thêm: code ví dụ JSP Servlet login bằng Facebook)

Đăng nhập ứng dụng Java Web bằng tài khoản Google

Ở bài này mình sẽ hướng dẫn viết ứng dụng java web bằng JSP – Servlet để truy cập tài khoản google.

Đầu tiên ta tạo một ứng dụng trên google và enable chức năng đăng nhập bằng tài khoản google cho web application.

(Xem lại: Tạo ứng dụng google+ để đăng nhập thay tài khoản)

Ví dụ, ở đây mình tạo ứng dụng JSPServlet-AccessGoogle:

  • client-id = “352140522561-vpmetjr6bjce1vod9b0cppihhbcgdesh.apps.googleusercontent.com”
  • client-secret = “dujlslz823Da_oyjQ1JJtTbX”

Ví dụ ứng dụng google để login

Tạo ứng dụng Java Web với JSP – Servlet

Ở đây mình dùng server là tomcat 8

Code ví dụ JSP Servlet login bằng Google (Gmail/Google+)

Mình dùng thư viện org.apache.httpcomponents (httpclient, httpcore, fluent) để gửi request từ bên trong class servlet, thư viện gson để convert dữ liệu từ dạng json và ngược lại. (mấy chức năng này viết khá dài nên mình dùng thư viên cho nhanh)

(Download các thư viện trên tại đây)

Class Constants.java:

Dùng để lưu client_id, client_secret, redirect_uri của ứng dung JSPServet-AccessGoogle

package stackjava.com.accessgoogle.common;

public class Constants {
  public static String GOOGLE_CLIENT_ID = "352140522561-vpmetjr6bjce1vod9b0cppihhbcgdesh.apps.googleusercontent.com";
  public static String GOOGLE_CLIENT_SECRET = "dujlslz823Da_oyjQ1JJtTbX";
  public static String GOOGLE_REDIRECT_URI = "http://localhost:8080/AccessGoogle/login-google";
  public static String GOOGLE_LINK_GET_TOKEN = "https://accounts.google.com/o/oauth2/token";
  public static String GOOGLE_LINK_GET_USER_INFO = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=";
  public static String GOOGLE_GRANT_TYPE = "authorization_code";
}

Trang login

<html>
<head>
  <title>Login</title>
</head>
<body>
  <h1>login</h1>
  <a href="https://accounts.google.com/o/oauth2/auth?scope=email&redirect_uri=http://localhost:8080/AccessGoogle/login-google&response_type=code
    &client_id=352140522561-vpmetjr6bjce1vod9b0cppihhbcgdesh.apps.googleusercontent.com&approval_prompt=force">Login With Google</a>	
</body>
</html>

Đường link https://accounts.google.com/o/oauth2/...force dùng để gọi hộp thoại đăng nhập và cài đặt URL chuyển hướng

 ví dụ đăng nhập java web bằng tài khoản gmail

Sau khi bạn chọn tài khoản để đăng nhập, google sẽ gửi một đoạn mã (code) tới url “http://localhost:8080/AccessGoogle/login-google” để server của bạn xử lý.

Class Servlet

package stackjava.com.accessgoogle.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 stackjava.com.accessgoogle.common.GooglePojo;
import stackjava.com.accessgoogle.common.GoogleUtils;

@WebServlet("/login-google")
public class LoginGoogleServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public LoginGoogleServlet() {
    super();
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String code = request.getParameter("code");

    if (code == null || code.isEmpty()) {
      RequestDispatcher dis = request.getRequestDispatcher("login.jsp");
      dis.forward(request, response);
    } else {
      String accessToken = GoogleUtils.getToken(code);
      GooglePojo googlePojo = GoogleUtils.getUserInfo(accessToken);
      request.setAttribute("id", googlePojo.getId());
      request.setAttribute("name", googlePojo.getName());
      request.setAttribute("email", googlePojo.getEmail());
      RequestDispatcher dis = request.getRequestDispatcher("index.jsp");
      dis.forward(request, response);
    }

  }

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

}

LoginGoogleServlet.java sẽ nhận đoạn mã trả về từ google, đổi mã đó thành access-token rồi dùng access-token để truy cập các thông tin trong tài khoản google như email, name, id…

Class GoogleUtils.java dùng để gửi truy vấn tới google (đổi code sang access-token, lấy thông tin trong tài khoản google)

package stackjava.com.accessgoogle.common;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;

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

public class GoogleUtils {

  public static String getToken(final String code) throws ClientProtocolException, IOException {
    String response = Request.Post(Constants.GOOGLE_LINK_GET_TOKEN)
        .bodyForm(Form.form().add("client_id", Constants.GOOGLE_CLIENT_ID)
            .add("client_secret", Constants.GOOGLE_CLIENT_SECRET)
            .add("redirect_uri",Constants.GOOGLE_REDIRECT_URI).add("code", code)
            .add("grant_type", Constants.GOOGLE_GRANT_TYPE).build())
        .execute().returnContent().asString();

      JsonObject jobj = new Gson().fromJson(response, JsonObject.class);
      String accessToken = jobj.get("access_token").toString().replaceAll("\"", "");
      return accessToken;
  }

  public static GooglePojo getUserInfo(final String accessToken) throws ClientProtocolException, IOException {
    String link = Constants.GOOGLE_LINK_GET_USER_INFO + accessToken;
    String response = Request.Get(link).execute().returnContent().asString();
    GooglePojo googlePojo = new Gson().fromJson(response, GooglePojo.class);
    System.out.println(googlePojo);
    return googlePojo;

  }

}

Token trả về từ google có dạng:

{
  "access_token" : "ya29.GlubBQa0s8EM2g2T5W2...",
  "expires_in" : 3600,
  "id_token" : "eyJh...",
  "token_type" : "Bearer"
}

Thông tin tài khoản trả về từ google có dạng:

{
 "id": "your_id",
 "email": "your_email",
 "verified_email": true,
 "name": "",
 "given_name": "",
 "family_name": "",
 "picture": "https://lh3.googleusercontent..."
}

Class GooglePojo.java gồm các thuộc tính tương ứng với các thông tin trong tài khoản google trả về.

package stackjava.com.accessgoogle.common;

public class GooglePojo {

  private String id;
  private String email;
  private boolean verified_email;
  private String name;
  private String given_name;
  private String family_name;
  private String link;
  private String picture;

  // getter-setter
}

Trang index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<html>
<head>
<title>index</title>
</head>
<body>
  <h1>Index</h1>
  <%
    String id = request.getAttribute("id").toString();
    String name = request.getAttribute("name").toString();
    String email = request.getAttribute("email").toString();
    out.print("Id: " + id);
    out.print("<br/>Name: " + name);
    out.print("<br/>Email: " + email);
  %>
</body>
</html>

Demo:

Code ví dụ JSP Servlet login bằng Google (Gmail/Google+)

Chọn tài khoản google để tiến hành đăng nhập

Code ví dụ JSP Servlet login bằng Google (Gmail/Google+)

Kết quả:

Code ví dụ JSP Servlet login bằng Google (Gmail/Google+)

Code ví dụ JSP Servlet login bằng Google (Gmail/Google+) stackjava.com

Okay, Done!

Download code ví dụ trên tại đây.

 

References:

https://www.logicbig.com/tutorials/java-ee-tutorial/java-servlet/servlet-oauth.html

http://productdesignsagain.blogspot.com/2016/12/integrating-google-social-media-login.html

stackjava.com