CODEXE

Google OAuth 2.0

Prerequisites

  1. Get Google API Access credentials (Client ID, Client Secret). Set from https://code.google.com/apis/console/

The process of OAuth is shown in the figure

  1. Use the client id and secret to go to the specific link provided by google to get the authorization code. The code will be retrun to the callback url.
  2. Use the code to get the access token
  3. Use the access token to get user info

GoogleOAuthHelper - Contains all APIs to get the access token and user info. What you should do is just make the CLIENT_ID, CLIENT_SECRET, CALLBACK_URI to your own value.


 public class GoogleOAuthHelper {
	/**
	 * Please provide a value for the CLIENT_ID constant before proceeding, set this up at https://code.google.com/apis/console/
	 */
	private static final String CLIENT_ID = "xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
	/**
	 * Please provide a value for the CLIENT_SECRET constant before proceeding, set this up at https://code.google.com/apis/console/
	 */
	private static final String CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxx";

	/**
	 * Callback URI that google will redirect to after successful authentication
	 */
	private static final String CALLBACK_URI = "http://localhost:8080/oauth/google";//http://localhost:8080/oauth/google
	
	// start google authentication constants
	private static final Collection SCOPE = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email".split(";"));
	private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
	 
	private static final JsonFactory JSON_FACTORY = new JacksonFactory();
	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
	// end google authentication constants
	
	private String stateToken;
	
	private final GoogleAuthorizationCodeFlow flow;
	
	/**
	 * Constructor initializes the Google Authorization Code Flow with CLIENT ID, SECRET, and SCOPE 
	 */
	public GoogleOAuthHelper() {
		flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
				JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE).build();
		generateStateToken();
	}

	/**
	 * Builds a login URL based on client ID, secret, callback URI, and scope 
	 */
	public String getAuthCodeURL() {
		
		final GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
	
		return url.setRedirectUri(CALLBACK_URI).setState(stateToken).build();
	}
	
	/**
	 * Generates a secure state token 
	 */
	private void generateStateToken(){

		SecureRandom sr1 = new SecureRandom();

		stateToken = "google;"+sr1.nextInt();

	}

	/**
	 * Accessor for state token
	 */
	public String getStateToken(){
		return stateToken;
	}

	/**
	 * Expects an Authentication Code, and makes an authenticated request for the user's profile information
	 * @return JSON formatted user profile information
	 * @param authCode authentication code provided by google
	 */
	public String getUserInfoJson(final String authCode) throws IOException {
		try {
			//1.get access token
			final GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(CALLBACK_URI).execute ();
			final Credential credential = flow.createAndStoreCredential(response, null);
			final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
			//2.user access token to get user info
			final GenericUrl url = new GenericUrl(USER_INFO_URL);
			final HttpRequest request = requestFactory.buildGetRequest(url);
			request.getHeaders().setContentType("application/json");
			final String jsonIdentity = request.execute().parseAsString();
			return jsonIdentity;
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
              

OAuthGoogleClServlet - Callback URI to get access token and user info



@WebServlet("/oauth/google")            	
public class OAuthGoogleClServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OAuthGoogleClServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//get google user's basic info
		//exact code and get access token
	
		String code = request.getParameter("code");
		if(code!=null) {
			GoogleOAuthHelper helper = new GoogleOAuthHelper();
			String userProfile = helper.getUserInfoJson(code);
			//extract user info and save to database
			JsonParser parser = new JsonParser();
			JsonObject userJson = parser.parse(userProfile).getAsJsonObject();
			String email = userJson.get("email").getAsString();
			System.out.println(email);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
            	

In the front-end page, add the HTML code.


              	<a class="btn btn-group-justified text-center" href="/login/google" style="background-color:#D0422A;color:white" href=“”><img src="/images/google.png" style="height:20px"> Google OAuth</a>
              

The "/login/google" is mainly to get the code.


@WebServlet("/login/google")   
public class LoginGoogleClServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginGoogleClServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//go to get auth code form google auth server
		HttpSession session = request.getSession(false);
		GoogleOAuthHelper helper = new GoogleOAuthHelper();
		String url = helper.getAuthCodeURL();
		//go to google login page to get the auth code
		response.sendRedirect(url);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
}