Exemplo n.º 1
0
  public URI createRedirectUri() {
    Map<String, String> parameters = Maps.newHashMap();
    parameters.put("response_type", "code");
    parameters.put("client_id", clientId);
    parameters.put("redirect_uri", uriBuilder.forPath(OAuthCallbackServlet.PATH).toString());
    parameters.put("scope", Joiner.on(" ").join(SCOPE));
    parameters.put("access_type", "online");
    parameters.put("state", uriBuilder.forPath("/").toString());

    try {
      return new URI(
          "https",
          "accounts.google.com",
          "/o/oauth2/auth",
          buildKeyValueString(parameters, false),
          null);
    } catch (URISyntaxException e) {
      throw new IllegalArgumentException(e);
    }
  }
Exemplo n.º 2
0
  public UserId determineUserId(String code) throws IOException {
    Map<String, String> parameters = Maps.newHashMap();
    parameters.put("code", code);
    parameters.put("client_id", clientId);
    parameters.put("client_secret", clientSecret);
    parameters.put("redirect_uri", uriBuilder.forPath(OAuthCallbackServlet.PATH).toString());
    parameters.put("grant_type", "authorization_code");

    HTTPRequest fetchRequest =
        new HTTPRequest(new URL("https://accounts.google.com/o/oauth2/token"), HTTPMethod.POST);
    fetchRequest.setPayload(buildKeyValueString(parameters, true).getBytes());
    HTTPResponse response = urlFetchService.fetch(fetchRequest);
    JsonObject object = jsonParser.parse(new String(response.getContent())).getAsJsonObject();
    String access_token = object.get("access_token").getAsString();

    HTTPRequest secondRequest =
        new HTTPRequest(new URL("https://www.googleapis.com/oauth2/v1/userinfo"));
    secondRequest.addHeader(
        new HTTPHeader("Authorization", String.format("Bearer %s", access_token)));
    response = urlFetchService.fetch(secondRequest);
    object = jsonParser.parse(new String(response.getContent())).getAsJsonObject();

    return UserId.fromString(object.get("id").getAsString());
  }