Skip to content

Commit d533f36

Browse files
committed
Merge pull request GoogleCloudPlatform#50 from GoogleCloudPlatform/appidentity
Add App Identity example to assert identity to Google APIs.
2 parents 92907e5 + 4fc5990 commit d533f36

File tree

4 files changed

+172
-0
lines changed

4 files changed

+172
-0
lines changed

appengine/appidentity/pom.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,23 @@ Copyright 2015 Google Inc. All Rights Reserved.
3333
<artifactId>appengine-api-1.0-sdk</artifactId>
3434
<version>${appengine.target.version}</version>
3535
</dependency>
36+
<dependency>
37+
<groupId>com.google.guava</groupId>
38+
<artifactId>guava</artifactId>
39+
<version>19.0</version>
40+
</dependency>
3641
<dependency>
3742
<groupId>javax.servlet</groupId>
3843
<artifactId>servlet-api</artifactId>
3944
<version>2.5</version>
4045
<type>jar</type>
4146
<scope>provided</scope>
4247
</dependency>
48+
<dependency>
49+
<groupId>org.json</groupId>
50+
<artifactId>json</artifactId>
51+
<version>20151123</version>
52+
</dependency>
4353

4454
<!-- Test Dependencies -->
4555
<dependency>
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.example.appengine.appidentity;
17+
18+
import com.google.appengine.api.appidentity.AppIdentityService;
19+
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
20+
import com.google.common.io.CharStreams;
21+
22+
import org.json.JSONObject;
23+
import org.json.JSONTokener;
24+
25+
import java.io.InputStream;
26+
import java.io.InputStreamReader;
27+
import java.io.OutputStreamWriter;
28+
import java.net.HttpURLConnection;
29+
import java.net.URL;
30+
import java.nio.charset.StandardCharsets;
31+
import java.util.ArrayList;
32+
33+
@SuppressWarnings("serial")
34+
class UrlShortener {
35+
// [START asserting_identity_to_Google_APIs]
36+
/**
37+
* Returns a shortened URL by calling the Google URL Shortener API.
38+
*
39+
* <p>Note: Error handling elided for simplicity.
40+
*/
41+
public String createShortUrl(String longUrl) throws Exception {
42+
ArrayList<String> scopes = new ArrayList<String>();
43+
scopes.add("https://www.googleapis.com/auth/urlshortener");
44+
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
45+
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
46+
// The token asserts the identity reported by appIdentity.getServiceAccountName()
47+
JSONObject request = new JSONObject();
48+
request.put("longUrl", longUrl);
49+
50+
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
51+
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
52+
connection.setDoOutput(true);
53+
connection.setRequestMethod("POST");
54+
connection.addRequestProperty("Content-Type", "application/json");
55+
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
56+
57+
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
58+
request.write(writer);
59+
writer.close();
60+
61+
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
62+
// Note: Should check the content-encoding.
63+
// Any JSON parser can be used; this one is used for illustrative purposes.
64+
JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
65+
JSONObject response = new JSONObject(response_tokens);
66+
return (String) response.get("id");
67+
} else {
68+
try (InputStream s = connection.getErrorStream();
69+
InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
70+
throw new RuntimeException(String.format(
71+
"got error (%d) response %s from %s",
72+
connection.getResponseCode(),
73+
CharStreams.toString(r),
74+
connection.toString()));
75+
}
76+
}
77+
}
78+
// [END asserting_identity_to_Google_APIs]
79+
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.example.appengine.appidentity;
17+
18+
import com.google.appengine.api.users.UserService;
19+
import com.google.appengine.api.users.UserServiceFactory;
20+
21+
import java.io.IOException;
22+
import java.io.PrintWriter;
23+
import java.net.URLDecoder;
24+
25+
import javax.servlet.http.HttpServlet;
26+
import javax.servlet.http.HttpServletRequest;
27+
import javax.servlet.http.HttpServletResponse;
28+
29+
@SuppressWarnings("serial")
30+
public class UrlShortenerServlet extends HttpServlet {
31+
private final UrlShortener shortener;
32+
33+
public UrlShortenerServlet() {
34+
shortener = new UrlShortener();
35+
}
36+
37+
@Override
38+
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
39+
PrintWriter w = resp.getWriter();
40+
w.println("<!DOCTYPE html>");
41+
w.println("<meta charset=\"utf-8\">");
42+
w.println("<title>Asserting Identity to Google APIs - App Engine App Identity Example</title>");
43+
w.println("<form method=\"post\">");
44+
w.println("<label for=\"longUrl\">URL:</label>");
45+
w.println("<input id=\"longUrl\" name=\"longUrl\" type=\"text\">");
46+
w.println("<input type=\"submit\" value=\"Shorten\">");
47+
w.println("</form>");
48+
}
49+
50+
@Override
51+
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
52+
resp.setContentType("text/plain");
53+
String longUrl = req.getParameter("longUrl");
54+
if (longUrl == null) {
55+
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing longUrl parameter");
56+
return;
57+
}
58+
59+
String shortUrl;
60+
PrintWriter w = resp.getWriter();
61+
try {
62+
shortUrl = shortener.createShortUrl(longUrl);
63+
} catch (Exception e) {
64+
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
65+
w.println("error shortening URL: " + longUrl);
66+
e.printStackTrace(w);
67+
return;
68+
}
69+
70+
w.print("long URL: ");
71+
w.println(longUrl);
72+
w.print("short URL: ");
73+
w.println(shortUrl);
74+
}
75+
}

appengine/appidentity/src/main/webapp/WEB-INF/web.xml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,16 @@
77
<servlet-name>appidentity</servlet-name>
88
<servlet-class>com.example.appengine.appidentity.IdentityServlet</servlet-class>
99
</servlet>
10+
<servlet>
11+
<servlet-name>urlshortener</servlet-name>
12+
<servlet-class>com.example.appengine.appidentity.UrlShortenerServlet</servlet-class>
13+
</servlet>
1014
<servlet-mapping>
1115
<servlet-name>appidentity</servlet-name>
1216
<url-pattern>/</url-pattern>
1317
</servlet-mapping>
18+
<servlet-mapping>
19+
<servlet-name>urlshortener</servlet-name>
20+
<url-pattern>/shorten</url-pattern>
21+
</servlet-mapping>
1422
</web-app>

0 commit comments

Comments
 (0)