Skip to content

Commit 8d133db

Browse files
committed
Add App Identity example to assert identity to Google APIs.
This sample is copied almost exactly from https://cloud.google.com/appengine/docs/java/appidentity/#asserting_identity_to_google_apis I also add a servlet for the sample code so that it can be more easily demonstrated and manually tested.
1 parent 7dfb03b commit 8d133db

File tree

4 files changed

+169
-0
lines changed

4 files changed

+169
-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: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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+
import org.json.JSONObject;
22+
import org.json.JSONTokener;
23+
24+
import java.io.InputStream;
25+
import java.io.InputStreamReader;
26+
import java.io.OutputStreamWriter;
27+
import java.net.HttpURLConnection;
28+
import java.net.URL;
29+
import java.nio.charset.StandardCharsets;
30+
import java.util.ArrayList;
31+
32+
@SuppressWarnings("serial")
33+
class UrlShortener {
34+
// [START asserting_identity_to_Google_APIs]
35+
public String createShortUrl(String longUrl) throws Exception {
36+
try {
37+
ArrayList<String> scopes = new ArrayList<String>();
38+
scopes.add("https://www.googleapis.com/auth/urlshortener");
39+
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
40+
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
41+
// The token asserts the identity reported by appIdentity.getServiceAccountName()
42+
JSONObject request = new JSONObject();
43+
request.put("longUrl", longUrl);
44+
45+
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
46+
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
47+
connection.setDoOutput(true);
48+
connection.setRequestMethod("POST");
49+
connection.addRequestProperty("Content-Type", "application/json");
50+
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
51+
52+
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
53+
request.write(writer);
54+
writer.close();
55+
56+
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
57+
// Note: Should check the content-encoding.
58+
// Any JSON parser can be used; this one is used for illustrative purposes.
59+
JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
60+
JSONObject response = new JSONObject(response_tokens);
61+
return (String) response.get("id");
62+
} else {
63+
try (InputStream s = connection.getErrorStream();
64+
InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
65+
throw new RuntimeException(String.format(
66+
"got error (%d) response %s from %s",
67+
connection.getResponseCode(),
68+
CharStreams.toString(r),
69+
connection.toString()));
70+
}
71+
}
72+
} catch (Exception e) {
73+
// Error handling elided.
74+
throw e;
75+
}
76+
}
77+
// [END asserting_identity_to_Google_APIs]
78+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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("<form method='post'>");
42+
w.println("<label for='longUrl'>URL:</label>");
43+
w.println("<input id='longUrl' name='longUrl' type='text'>");
44+
w.println("<input type='submit' value='Shorten'>");
45+
w.println("</form>");
46+
}
47+
48+
@Override
49+
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
50+
resp.setContentType("text/plain");
51+
String longUrl = req.getParameter("longUrl");
52+
if (longUrl == null) {
53+
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing longUrl parameter");
54+
return;
55+
}
56+
57+
String shortUrl;
58+
PrintWriter w = resp.getWriter();
59+
try {
60+
shortUrl = shortener.createShortUrl(longUrl);
61+
} catch (Exception e) {
62+
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
63+
w.println("error shortening URL: " + longUrl);
64+
e.printStackTrace(w);
65+
return;
66+
}
67+
68+
w.print("long URL: ");
69+
w.println(longUrl);
70+
w.print("short URL: ");
71+
w.println(shortUrl);
72+
}
73+
}

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)