Search in sources :

Example 1 with JsonWebSignature

use of com.google.api.client.json.webtoken.JsonWebSignature in project google-auth-library-java by google.

the class MockTokenServerTransport method buildRequest.

@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
    buildRequestCount++;
    if (error != null) {
        throw error;
    }
    int questionMarkPos = url.indexOf('?');
    final String urlWithoutQUery = (questionMarkPos > 0) ? url.substring(0, questionMarkPos) : url;
    final String query = (questionMarkPos > 0) ? url.substring(questionMarkPos + 1) : "";
    if (urlWithoutQUery.equals(tokenServerUri.toString())) {
        return new MockLowLevelHttpRequest(url) {

            @Override
            public LowLevelHttpResponse execute() throws IOException {
                IOException responseError = responseErrorSequence.poll();
                if (responseError != null) {
                    throw responseError;
                }
                LowLevelHttpResponse response = responseSequence.poll();
                if (response != null) {
                    return response;
                }
                String content = this.getContentAsString();
                Map<String, String> query = TestUtils.parseQuery(content);
                String accessToken;
                String refreshToken = null;
                String foundId = query.get("client_id");
                if (foundId != null) {
                    if (!clients.containsKey(foundId)) {
                        throw new IOException("Client ID not found.");
                    }
                    String foundSecret = query.get("client_secret");
                    String expectedSecret = clients.get(foundId);
                    if (foundSecret == null || !foundSecret.equals(expectedSecret)) {
                        throw new IOException("Client secret not found.");
                    }
                    String grantType = query.get("grant_type");
                    if (grantType != null && grantType.equals("authorization_code")) {
                        String foundCode = query.get("code");
                        if (!codes.containsKey(foundCode)) {
                            throw new IOException("Authorization code not found");
                        }
                        refreshToken = codes.get(foundCode);
                    } else {
                        refreshToken = query.get("refresh_token");
                    }
                    if (!refreshTokens.containsKey(refreshToken)) {
                        throw new IOException("Refresh Token not found.");
                    }
                    accessToken = refreshTokens.get(refreshToken);
                } else if (query.containsKey("grant_type")) {
                    String grantType = query.get("grant_type");
                    if (!EXPECTED_GRANT_TYPE.equals(grantType)) {
                        throw new IOException("Unexpected Grant Type.");
                    }
                    String assertion = query.get("assertion");
                    JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
                    String foundEmail = signature.getPayload().getIssuer();
                    if (!serviceAccounts.containsKey(foundEmail)) {
                        throw new IOException("Service Account Email not found as issuer.");
                    }
                    accessToken = serviceAccounts.get(foundEmail);
                    String foundScopes = (String) signature.getPayload().get("scope");
                    if (foundScopes == null || foundScopes.length() == 0) {
                        throw new IOException("Scopes not found.");
                    }
                } else {
                    throw new IOException("Unknown token type.");
                }
                // Create the JSON response
                GenericJson refreshContents = new GenericJson();
                refreshContents.setFactory(JSON_FACTORY);
                refreshContents.put("access_token", accessToken);
                refreshContents.put("expires_in", expiresInSeconds);
                refreshContents.put("token_type", "Bearer");
                if (refreshToken != null) {
                    refreshContents.put("refresh_token", refreshToken);
                }
                String refreshText = refreshContents.toPrettyString();
                return new MockLowLevelHttpResponse().setContentType(Json.MEDIA_TYPE).setContent(refreshText);
            }
        };
    } else if (urlWithoutQUery.equals(OAuth2Utils.TOKEN_REVOKE_URI.toString())) {
        return new MockLowLevelHttpRequest(url) {

            @Override
            public LowLevelHttpResponse execute() throws IOException {
                Map<String, String> parameters = TestUtils.parseQuery(query);
                String token = parameters.get("token");
                if (token == null) {
                    throw new IOException("Token to revoke not found.");
                }
                // Token could be access token or refresh token so remove keys and values
                refreshTokens.values().removeAll(Collections.singleton(token));
                refreshTokens.remove(token);
                return new MockLowLevelHttpResponse().setContentType(Json.MEDIA_TYPE);
            }
        };
    }
    return super.buildRequest(method, url);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 2 with JsonWebSignature

use of com.google.api.client.json.webtoken.JsonWebSignature in project google-api-java-client by google.

the class MockTokenServerTransport method buildRequest.

@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
    if (url.equals(tokenServerUrl)) {
        MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) {

            @Override
            public LowLevelHttpResponse execute() throws IOException {
                String content = this.getContentAsString();
                Map<String, String> query = TestUtils.parseQuery(content);
                String accessToken = null;
                String foundId = query.get("client_id");
                if (foundId != null) {
                    if (!clients.containsKey(foundId)) {
                        throw new IOException("Client ID not found.");
                    }
                    String foundSecret = query.get("client_secret");
                    String expectedSecret = clients.get(foundId);
                    if (foundSecret == null || !foundSecret.equals(expectedSecret)) {
                        throw new IOException("Client secret not found.");
                    }
                    String foundRefresh = query.get("refresh_token");
                    if (!refreshTokens.containsKey(foundRefresh)) {
                        throw new IOException("Refresh Token not found.");
                    }
                    accessToken = refreshTokens.get(foundRefresh);
                } else if (query.containsKey("grant_type")) {
                    String grantType = query.get("grant_type");
                    if (!EXPECTED_GRANT_TYPE.equals(grantType)) {
                        throw new IOException("Unexpected Grant Type.");
                    }
                    String assertion = query.get("assertion");
                    JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
                    String foundEmail = signature.getPayload().getIssuer();
                    if (!serviceAccounts.containsKey(foundEmail)) {
                        throw new IOException("Service Account Email not found as issuer.");
                    }
                    accessToken = serviceAccounts.get(foundEmail);
                    String foundScopes = (String) signature.getPayload().get("scope");
                    if (foundScopes == null || foundScopes.length() == 0) {
                        throw new IOException("Scopes not found.");
                    }
                } else {
                    throw new IOException("Unknown token type.");
                }
                // Create the JSon response
                GenericJson refreshContents = new GenericJson();
                refreshContents.setFactory(JSON_FACTORY);
                refreshContents.put("access_token", accessToken);
                refreshContents.put("expires_in", 3600000);
                refreshContents.put("token_type", "Bearer");
                String refreshText = refreshContents.toPrettyString();
                MockLowLevelHttpResponse response = new MockLowLevelHttpResponse().setContentType(Json.MEDIA_TYPE).setContent(refreshText);
                return response;
            }
        };
        return request;
    }
    return super.buildRequest(method, url);
}
Also used : GenericJson(com.google.api.client.json.GenericJson) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature) IOException(java.io.IOException) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest)

Example 3 with JsonWebSignature

use of com.google.api.client.json.webtoken.JsonWebSignature in project google-auth-library-java by google.

the class ServiceAccountJwtAccessCredentialsTest method verifyJwtAccess.

private void verifyJwtAccess(Map<String, List<String>> metadata, String expectedEmail, URI expectedAudience, String expectedKeyId) throws IOException {
    assertNotNull(metadata);
    List<String> authorizations = metadata.get(AuthHttpConstants.AUTHORIZATION);
    assertNotNull("Authorization headers not found", authorizations);
    String assertion = null;
    for (String authorization : authorizations) {
        if (authorization.startsWith(JWT_ACCESS_PREFIX)) {
            assertNull("Multiple bearer assertions found", assertion);
            assertion = authorization.substring(JWT_ACCESS_PREFIX.length());
        }
    }
    assertNotNull("Bearer assertion not found", assertion);
    JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion);
    assertEquals(expectedEmail, signature.getPayload().getIssuer());
    assertEquals(expectedEmail, signature.getPayload().getSubject());
    assertEquals(expectedAudience.toString(), signature.getPayload().getAudience());
    assertEquals(expectedKeyId, signature.getHeader().getKeyId());
}
Also used : JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature)

Example 4 with JsonWebSignature

use of com.google.api.client.json.webtoken.JsonWebSignature in project google-auth-library-java by google.

the class ServiceAccountCredentialsTest method createAssertion_correct.

@Test
public void createAssertion_correct() throws IOException {
    PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
    List<String> scopes = Arrays.asList("scope1", "scope2");
    ServiceAccountCredentials credentials = ServiceAccountCredentials.newBuilder().setClientId(SA_CLIENT_ID).setClientEmail(SA_CLIENT_EMAIL).setPrivateKey(privateKey).setPrivateKeyId(SA_PRIVATE_KEY_ID).setScopes(scopes).setServiceAccountUser(SERVICE_ACCOUNT_USER).setProjectId(PROJECT_ID).build();
    JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
    long currentTimeMillis = Clock.SYSTEM.currentTimeMillis();
    String assertion = credentials.createAssertion(jsonFactory, currentTimeMillis);
    JsonWebSignature signature = JsonWebSignature.parse(jsonFactory, assertion);
    JsonWebToken.Payload payload = signature.getPayload();
    assertEquals(SA_CLIENT_EMAIL, payload.getIssuer());
    assertEquals(OAuth2Utils.TOKEN_SERVER_URI.toString(), payload.getAudience());
    assertEquals(currentTimeMillis / 1000, (long) payload.getIssuedAtTimeSeconds());
    assertEquals(currentTimeMillis / 1000 + 3600, (long) payload.getExpirationTimeSeconds());
    assertEquals(SERVICE_ACCOUNT_USER, payload.getSubject());
    assertEquals(Joiner.on(' ').join(scopes), payload.get("scope"));
}
Also used : PrivateKey(java.security.PrivateKey) JsonWebSignature(com.google.api.client.json.webtoken.JsonWebSignature) JsonFactory(com.google.api.client.json.JsonFactory) JsonWebToken(com.google.api.client.json.webtoken.JsonWebToken) Test(org.junit.Test)

Aggregations

JsonWebSignature (com.google.api.client.json.webtoken.JsonWebSignature)4 GenericJson (com.google.api.client.json.GenericJson)2 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)2 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)2 IOException (java.io.IOException)2 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)1 JsonFactory (com.google.api.client.json.JsonFactory)1 JsonWebToken (com.google.api.client.json.webtoken.JsonWebToken)1 PrivateKey (java.security.PrivateKey)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Test (org.junit.Test)1