Skip to content

Commit

Permalink
Merge pull request #50 from GoogleCloudPlatform/appidentity
Browse files Browse the repository at this point in the history
Add App Identity example to assert identity to Google APIs.
  • Loading branch information
tswast committed Jan 8, 2016
2 parents 92907e5 + 4fc5990 commit d533f36
Show file tree
Hide file tree
Showing 4 changed files with 172 additions and 0 deletions.
10 changes: 10 additions & 0 deletions appengine/appidentity/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,23 @@ Copyright 2015 Google Inc. All Rights Reserved.
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.target.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>

<!-- Test Dependencies -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.appengine.appidentity;

import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.common.io.CharStreams;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

@SuppressWarnings("serial")
class UrlShortener {
// [START asserting_identity_to_Google_APIs]
/**
* Returns a shortened URL by calling the Google URL Shortener API.
*
* <p>Note: Error handling elided for simplicity.
*/
public String createShortUrl(String longUrl) throws Exception {
ArrayList<String> scopes = new ArrayList<String>();
scopes.add("https://www.googleapis.com/auth/urlshortener");
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
// The token asserts the identity reported by appIdentity.getServiceAccountName()
JSONObject request = new JSONObject();
request.put("longUrl", longUrl);

URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
request.write(writer);
writer.close();

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Note: Should check the content-encoding.
// Any JSON parser can be used; this one is used for illustrative purposes.
JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
JSONObject response = new JSONObject(response_tokens);
return (String) response.get("id");
} else {
try (InputStream s = connection.getErrorStream();
InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
throw new RuntimeException(String.format(
"got error (%d) response %s from %s",
connection.getResponseCode(),
CharStreams.toString(r),
connection.toString()));
}
}
}
// [END asserting_identity_to_Google_APIs]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.appengine.appidentity;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class UrlShortenerServlet extends HttpServlet {
private final UrlShortener shortener;

public UrlShortenerServlet() {
shortener = new UrlShortener();
}

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter w = resp.getWriter();
w.println("<!DOCTYPE html>");
w.println("<meta charset=\"utf-8\">");
w.println("<title>Asserting Identity to Google APIs - App Engine App Identity Example</title>");
w.println("<form method=\"post\">");
w.println("<label for=\"longUrl\">URL:</label>");
w.println("<input id=\"longUrl\" name=\"longUrl\" type=\"text\">");
w.println("<input type=\"submit\" value=\"Shorten\">");
w.println("</form>");
}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
String longUrl = req.getParameter("longUrl");
if (longUrl == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing longUrl parameter");
return;
}

String shortUrl;
PrintWriter w = resp.getWriter();
try {
shortUrl = shortener.createShortUrl(longUrl);
} catch (Exception e) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
w.println("error shortening URL: " + longUrl);
e.printStackTrace(w);
return;
}

w.print("long URL: ");
w.println(longUrl);
w.print("short URL: ");
w.println(shortUrl);
}
}
8 changes: 8 additions & 0 deletions appengine/appidentity/src/main/webapp/WEB-INF/web.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@
<servlet-name>appidentity</servlet-name>
<servlet-class>com.example.appengine.appidentity.IdentityServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>urlshortener</servlet-name>
<servlet-class>com.example.appengine.appidentity.UrlShortenerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>appidentity</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>urlshortener</servlet-name>
<url-pattern>/shorten</url-pattern>
</servlet-mapping>
</web-app>

0 comments on commit d533f36

Please sign in to comment.