-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add App Identity example to assert identity to Google APIs. #50
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
appengine/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortener.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
} |
75 changes: 75 additions & 0 deletions
75
...gine/appidentity/src/main/java/com/example/appengine/appidentity/UrlShortenerServlet.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok for now, but I think we should probably move our samples to GSON or something else.