Skip to content

Commit e164536

Browse files
committed
Merge pull request #77 from GoogleCloudPlatform/appidentity
Add sample for asserting identity to third-party services
2 parents 9747002 + 9a2b0e7 commit e164536

File tree

4 files changed

+196
-7
lines changed

4 files changed

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

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: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/**
1+
/*
22
* Copyright 2015 Google Inc. All Rights Reserved.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,25 +13,21 @@
1313
* See the License for the specific language governing permissions and
1414
* limitations under the License.
1515
*/
16+
1617
package com.example.appengine.appidentity;
1718

1819
import static com.google.common.truth.Truth.assertThat;
19-
import static org.junit.Assert.fail;
20-
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;
3229
import org.junit.runners.JUnit4;
3330

34-
import java.io.File;
3531
import java.io.PrintWriter;
3632
import java.io.StringWriter;
3733

@@ -62,6 +58,10 @@ public void setUp() throws Exception {
6258
servletUnderTest = new IdentityServlet();
6359
}
6460

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

0 commit comments

Comments
 (0)