Close

Java Servlet - Servlet OAuth Examples

Java Servlet JAVA EE 

using OAuth and google api to login user to servlet based application

package com.logicbig.example;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;

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;
import java.io.IOException;

@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doPost (HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");

try {
String idToken = req.getParameter("id_token");
GoogleIdToken.Payload payLoad = IdTokenVerifierAndParser.getPayload(idToken);
String name = (String) payLoad.get("name");
String email = payLoad.getEmail();
System.out.println("User name: " + name);
System.out.println("User email: " + email);

HttpSession session = req.getSession(true);
session.setAttribute("userName", name);
req.getServletContext()
.getRequestDispatcher("/welcome-page.jsp").forward(req, resp);

} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.logicbig.example;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;

public class IdTokenVerifierAndParser {
private static final String GOOGLE_CLIENT_ID = "---- use your google Client ID here-----";

public static GoogleIdToken.Payload getPayload (String tokenString) throws Exception {

JacksonFactory jacksonFactory = new JacksonFactory();
GoogleIdTokenVerifier googleIdTokenVerifier =
new GoogleIdTokenVerifier(new NetHttpTransport(), jacksonFactory);

GoogleIdToken token = GoogleIdToken.parse(jacksonFactory, tokenString);

if (googleIdTokenVerifier.verify(token)) {
GoogleIdToken.Payload payload = token.getPayload();
if (!GOOGLE_CLIENT_ID.equals(payload.getAudience())) {
throw new IllegalArgumentException("Audience mismatch");
} else if (!GOOGLE_CLIENT_ID.equals(payload.getAuthorizedParty())) {
throw new IllegalArgumentException("Client ID mismatch");
}
return payload;
} else {
throw new IllegalArgumentException("id token cannot be verified");
}
}
}
Original Post




See Also