Skip to content

Commit 52f74d2

Browse files
committed
Add sample for asserting identity to third-party services
1 parent 49ceff8 commit 52f74d2

File tree

4 files changed

+201
-7
lines changed

4 files changed

+201
-7
lines changed
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* <p>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+
* <p>http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* <p>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.PublicCertificate;
19+
import com.google.appengine.api.appidentity.AppIdentityService;
20+
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
21+
import com.google.apphosting.api.ApiProxy;
22+
import com.google.apphosting.api.ApiProxy.Environment;
23+
24+
import java.io.ByteArrayInputStream;
25+
import java.io.InputStream;
26+
import java.io.IOException;
27+
import java.io.PrintWriter;
28+
import java.io.UnsupportedEncodingException;
29+
import java.security.cert.Certificate;
30+
import java.security.cert.CertificateException;
31+
import java.security.cert.CertificateFactory;
32+
import java.security.InvalidKeyException;
33+
import java.security.NoSuchAlgorithmException;
34+
import java.security.PublicKey;
35+
import java.security.Signature;
36+
import java.security.SignatureException;
37+
import java.util.Arrays;
38+
import java.util.Collection;
39+
40+
import javax.servlet.http.HttpServlet;
41+
import javax.servlet.http.HttpServletRequest;
42+
import javax.servlet.http.HttpServletResponse;
43+
44+
@SuppressWarnings("serial")
45+
public class SignForAppServlet extends HttpServlet {
46+
private final AppIdentityService appIdentity;
47+
48+
public SignForAppServlet() {
49+
appIdentity = AppIdentityServiceFactory.getAppIdentityService();
50+
}
51+
52+
// [START asserting_identity_to_other_services]
53+
// Note that the algorithm used by AppIdentity.signForApp() and
54+
// getPublicCertificatesForApp() is "SHA256withRSA"
55+
56+
private byte[] signBlob(byte[] blob) {
57+
AppIdentityService.SigningResult result = appIdentity.signForApp(blob);
58+
return result.getSignature();
59+
}
60+
61+
private byte[] getPublicCertificate() throws UnsupportedEncodingException {
62+
Collection<PublicCertificate> certs = appIdentity.getPublicCertificatesForApp();
63+
PublicCertificate publicCert = certs.iterator().next();
64+
return publicCert.getX509CertificateInPemFormat().getBytes("UTF-8");
65+
}
66+
67+
private Certificate parsePublicCertificate(byte[] publicCert)
68+
throws CertificateException, NoSuchAlgorithmException {
69+
InputStream stream = new ByteArrayInputStream(publicCert);
70+
CertificateFactory cf = CertificateFactory.getInstance("X.509");
71+
return cf.generateCertificate(stream);
72+
}
73+
74+
private boolean verifySignature(byte[] blob, byte[] blobSignature, PublicKey pk)
75+
throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
76+
Signature signature = Signature.getInstance("SHA256withRSA");
77+
signature.initVerify(pk);
78+
signature.update(blob);
79+
return signature.verify(blobSignature);
80+
}
81+
82+
private String simulateIdentityAssertion()
83+
throws CertificateException, UnsupportedEncodingException, NoSuchAlgorithmException,
84+
InvalidKeyException, SignatureException {
85+
// Simulate the sending app.
86+
String message = "abcdefg";
87+
byte[] blob = message.getBytes();
88+
byte[] blobSignature = signBlob(blob);
89+
byte[] publicCert = getPublicCertificate();
90+
91+
// Simulate the receiving app, which gets the certificate, blob, and signature.
92+
Certificate cert = parsePublicCertificate(publicCert);
93+
PublicKey pk = cert.getPublicKey();
94+
boolean isValid = verifySignature(blob, blobSignature, pk);
95+
96+
return String.format(
97+
"isValid=%b for message: %s\n\tsignature: %s\n\tpublic cert: %s",
98+
isValid,
99+
message,
100+
Arrays.toString(blobSignature),
101+
Arrays.toString(publicCert));
102+
}
103+
// [END asserting_identity_to_other_services]
104+
105+
@Override
106+
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
107+
resp.setContentType("text/plain");
108+
try {
109+
resp.getWriter().println(simulateIdentityAssertion());
110+
} catch (Exception e) {
111+
throw new RuntimeException(e);
112+
}
113+
}
114+
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77
<servlet-name>appidentity</servlet-name>
88
<servlet-class>com.example.appengine.appidentity.IdentityServlet</servlet-class>
99
</servlet>
10+
<servlet>
11+
<servlet-name>signforapp</servlet-name>
12+
<servlet-class>com.example.appengine.appidentity.SignForAppServlet</servlet-class>
13+
</servlet>
1014
<servlet>
1115
<servlet-name>urlshortener</servlet-name>
1216
<servlet-class>com.example.appengine.appidentity.UrlShortenerServlet</servlet-class>
@@ -15,6 +19,10 @@
1519
<servlet-name>appidentity</servlet-name>
1620
<url-pattern>/</url-pattern>
1721
</servlet-mapping>
22+
<servlet-mapping>
23+
<servlet-name>signforapp</servlet-name>
24+
<url-pattern>/sign</url-pattern>
25+
</servlet-mapping>
1826
<servlet-mapping>
1927
<servlet-name>urlshortener</servlet-name>
2028
<url-pattern>/shorten</url-pattern>

appengine/appidentity/src/test/java/com/example/appengine/appidentity/IdentityServletTest.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
/**
22
* Copyright 2015 Google Inc. All Rights Reserved.
33
*
4-
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* <p>Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
66
* You may obtain a copy of the License at
77
*
8-
* http://www.apache.org/licenses/LICENSE-2.0
8+
* <p>http://www.apache.org/licenses/LICENSE-2.0
99
*
10-
* Unless required by applicable law or agreed to in writing, software
10+
* <p>Unless required by applicable law or agreed to in writing, software
1111
* distributed under the License is distributed on an "AS IS" BASIS,
1212
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
* See the License for the specific language governing permissions and
@@ -16,16 +16,13 @@
1616
package com.example.appengine.appidentity;
1717

1818
import static com.google.common.truth.Truth.assertThat;
19-
import static org.junit.Assert.fail;
2019
import static org.mockito.Mockito.mock;
2120
import static org.mockito.Mockito.when;
2221

23-
import com.google.appengine.tools.development.ApiProxyLocal;
2422
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
25-
import com.google.apphosting.api.ApiProxy;
2623
import org.mockito.Mock;
27-
import org.mockito.Mockito;
2824
import org.mockito.MockitoAnnotations;
25+
import org.junit.After;
2926
import org.junit.Before;
3027
import org.junit.Test;
3128
import org.junit.runner.RunWith;
@@ -62,6 +59,10 @@ public void setUp() throws Exception {
6259
servletUnderTest = new IdentityServlet();
6360
}
6461

62+
@After public void tearDown() {
63+
helper.tearDown();
64+
}
65+
6566
@Test
6667
public void doGet_defaultEnvironment_writesResponse() throws Exception {
6768
servletUnderTest.doGet(mockRequest, mockResponse);
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* Copyright 2016 Google Inc. All Rights Reserved.
3+
*
4+
* <p>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+
* <p>http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* <p>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 static com.google.common.truth.Truth.assertThat;
19+
import static org.mockito.Mockito.mock;
20+
import static org.mockito.Mockito.when;
21+
22+
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
23+
import org.mockito.Mock;
24+
import org.mockito.MockitoAnnotations;
25+
import org.junit.After;
26+
import org.junit.Before;
27+
import org.junit.Test;
28+
import org.junit.runner.RunWith;
29+
import org.junit.runners.JUnit4;
30+
31+
import java.io.File;
32+
import java.io.PrintWriter;
33+
import java.io.StringWriter;
34+
35+
import javax.servlet.http.HttpServletRequest;
36+
import javax.servlet.http.HttpServletResponse;
37+
38+
/** Unit tests for {@link SignForAppServlet}. */
39+
@RunWith(JUnit4.class)
40+
public class SignForAppServletTest {
41+
42+
private final LocalServiceTestHelper helper = new LocalServiceTestHelper();
43+
44+
@Mock private HttpServletRequest mockRequest;
45+
@Mock private HttpServletResponse mockResponse;
46+
private StringWriter responseWriter;
47+
private SignForAppServlet servletUnderTest;
48+
49+
@Before public void setUp() throws Exception {
50+
MockitoAnnotations.initMocks(this);
51+
helper.setUp();
52+
53+
// Set up a fake HTTP response.
54+
responseWriter = new StringWriter();
55+
when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
56+
57+
servletUnderTest = new SignForAppServlet();
58+
}
59+
60+
@After public void tearDown() {
61+
helper.tearDown();
62+
}
63+
64+
@Test public void doGet_defaultEnvironment_successfullyVerifiesSignature() throws Exception {
65+
servletUnderTest.doGet(mockRequest, mockResponse);
66+
67+
assertThat(responseWriter.toString())
68+
.named("SignForAppServlet response")
69+
.contains("isValid=true for message: abcdefg");
70+
}
71+
}

0 commit comments

Comments
 (0)