示例#1
0
  private void handleAuthorization(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    PrintWriter writer = resp.getWriter();
    if (req.getParameter("error") != null) {
      writer.append(req.getParameter("error"));
      return;
    }

    String code = req.getParameter("code");

    String redir = (String) req.getSession().getAttribute("redir");
    req.getSession().setAttribute("redir", null);

    if (code == null || redir == null) {
      resp.sendRedirect("/");
      return;
    }

    StringBuilder postParameters = new StringBuilder();
    postParameters.append(para("code", code)).append("&");
    postParameters.append(para("client_id", Configuration.googleClientId())).append("&");
    postParameters.append(para("client_secret", Configuration.googleClientSecret())).append("&");
    postParameters.append(para("redirect_uri", redir)).append("&");
    postParameters.append(para("grant_type", "authorization_code"));
    URL url = new URL("https://accounts.google.com/o/oauth2/token");
    URLConnection urlConnection = url.openConnection();

    ((HttpURLConnection) urlConnection).setRequestMethod("POST");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Content-Length", "" + postParameters.toString().length());

    // Create I/O streams
    DataOutputStream outStream = new DataOutputStream(urlConnection.getOutputStream());
    // Send request
    outStream.writeBytes(postParameters.toString());
    outStream.flush();
    outStream.close();

    String googleJson = toString(urlConnection.getInputStream());

    JsonObject jsonObject = (JsonObject) JsonParser.parse(googleJson);
    String accessToken = jsonObject.requiredString("access_token");

    // get some info about the user with the access token
    String getStr =
        "https://www.googleapis.com/oauth2/v1/userinfo?" + para("access_token", accessToken);
    URLConnection inconn = new URL(getStr).openConnection();
    String gsstr;
    try (InputStream is = inconn.getInputStream()) {
      gsstr = toString(is);
    }

    updateUserLogin(req, gsstr);
    redirToLandingPage(req, resp);
  }
示例#2
0
  private void updateUserLogin(HttpServletRequest req, String gsstr) throws IOException {
    JsonNode googleAuth = JsonParser.parse(gsstr);
    JsonObject objnode = (JsonObject) googleAuth;

    String googleId = objnode.requiredString("id");
    boolean isAdmin = Configuration.adminGoogleIds().contains(googleId);
    objnode.put("admin", isAdmin);

    System.out.println("Setting user logged in " + objnode);
    req.getSession().setAttribute("user", objnode);
  }