com.google.api.client.auth.openidconnect.IdToken Java Examples

The following examples show how to use com.google.api.client.auth.openidconnect.IdToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FirebaseTokenTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testFirebaseTokenFromIdToken() {
  IdToken.Payload payload = new IdToken.Payload()
      .setSubject("testUser")
      .setIssuer("test-project-id")
      .set("email", "[email protected]")
      .set("email_verified", true)
      .set("name", "Test User")
      .set("picture", "https://picture.url")
      .set("custom", "claim");

  FirebaseToken firebaseToken = new FirebaseToken(payload);

  assertEquals("testUser", firebaseToken.getUid());
  assertEquals("test-project-id", firebaseToken.getIssuer());
  assertEquals("[email protected]", firebaseToken.getEmail());
  assertTrue(firebaseToken.isEmailVerified());
  assertEquals("Test User", firebaseToken.getName());
  assertEquals("https://picture.url", firebaseToken.getPicture());
  assertEquals("claim", firebaseToken.getClaims().get("custom"));
  assertEquals(7, firebaseToken.getClaims().size());
}
 
Example #2
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testSetResponseClass() throws IOException {
  TokenRequest request = new TokenRequest(new AccessTokenTransport(), JSON_FACTORY, AUTHORIZATION_SERVER_URL, "foo")
      .setResponseClass(IdTokenResponse.class);
  assertEquals(IdTokenResponse.class, request.getResponseClass());
  TokenResponse response = request.execute();
  assertTrue(response instanceof IdTokenResponse);
  IdTokenResponse tokenResponse = (IdTokenResponse)response;
  IdToken idToken = tokenResponse.parseIdToken();
  assertEquals("John Doe", idToken.getPayload().get("name"));
}
 
Example #3
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 * Validates the access token issued with an ID Token, by comparing the result of the access token hash
 * with the 'at_hash' claim contained on the ID Token.
 * @param accessTokenString the access token to hash
 * @param idTokenString the ID Token were the 'at_hash' can be found
 * @return true if the result of the hashed access token is equal to the 'at_hash' claim.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @see <a hfre="http://openid.net/specs/openid-connect-core-1_0.html#ImplicitTokenValidation">http://openid.net/specs/openid-connect-core-1_0.html#ImplicitTokenValidation</a>
 */
private boolean isValidAccessToken(String accessTokenString, String idTokenString) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    boolean isValidAt = false;
    if (!TextUtils.isEmpty(accessTokenString) && !TextUtils.isEmpty(idTokenString)) {
        IdToken idToken = IdToken.parse(new GsonFactory(), idTokenString);
        String alg = idToken.getHeader().getAlgorithm();
        byte[] atBytes = accessTokenString.getBytes("UTF-8");
        String atHash = idToken.getPayload().getAccessTokenHash();

        String forgedAtHash;
        if ("HS256".equals(alg) || "RS256".equals(alg)) {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(atBytes, 0, atBytes.length);
            atBytes = digest.digest();
            atBytes = Arrays.copyOfRange(atBytes, 0, atBytes.length / 2);
            forgedAtHash = Base64.encodeToString(atBytes, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);

            Log.d(TAG, "Alg : " + alg);
            Log.d(TAG, "Receive at_hash : " + atHash);
            Log.d(TAG, "Forged at_hash  : " + forgedAtHash);

            isValidAt = atHash.equals(forgedAtHash);
        } else {
            Log.w(TAG, "Unsupported alg claim : " +alg + ". Supported alg are HS256, RS256");
        }

    } else {
        Log.w(TAG, "Can't verify access token, AT or idToken empty");
    }

    return true;//isValidAt;
}
 
Example #4
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 * Validates an IdToken.
 * TODO: Look into verifying the token nonce as well?
 *
 * @param idTokenString the IdToken to validate
 * @return true if the idToken is valid, false otherwise.
 * @throws IOException when the IdToken can not be parse.
 * @see IdTokenVerifier#verify(IdToken)
 */
private boolean isValidIdToken(@NonNull String idTokenString) throws IOException {

    List<String> audiences = Collections.singletonList(clientId);
    IdTokenVerifier verifier = new IdTokenVerifier.Builder()
            .setAudience(audiences)
            .setAcceptableTimeSkewSeconds(1000)
            .setIssuer(issuerId)
            .build();

    IdToken idToken = IdToken.parse(new GsonFactory(), idTokenString);

    return true;//verifier.verify(idToken);
}
 
Example #5
Source File: PluginTest.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private String createIdToken(PrivateKey privateKey, Map<String, Object> keyValues) throws Exception {
    JsonWebSignature.Header header = new JsonWebSignature.Header()
        .setAlgorithm("RS256");
    IdToken.Payload payload = new IdToken.Payload()
        .setIssuer("issuer")
        .setSubject(TEST_USER_USERNAME)
        .setAudience(Collections.singletonList("clientId"))
        .setAudience(System.currentTimeMillis() / 60 + 5)
        .setIssuedAtTimeSeconds(System.currentTimeMillis() / 60);
    for(Map.Entry<String, Object> keyValue : keyValues.entrySet()) {
        payload.set(keyValue.getKey(), keyValue.getValue());
    }

    return JsonWebSignature.signUsingRsaSha256(privateKey, JSON_FACORY, header, payload);
}
 
Example #6
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private String getField(IdToken idToken, String fullNameFieldName) {
    Object value = getField(idToken.getPayload(), fullNameFieldName);
    if(value != null) {
        return String.valueOf(value);
    }
    return null;
}
 
Example #7
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private UsernamePasswordAuthenticationToken loginAndSetUserData(String userName, IdToken idToken, GenericJson userInfo) throws IOException {

        GrantedAuthority[] grantedAuthorities = determineAuthorities(idToken, userInfo);
        if(LOGGER.isLoggable(Level.FINEST)) {
		    StringBuilder grantedAuthoritiesAsString = new StringBuilder("(");
		    for(GrantedAuthority grantedAuthority : grantedAuthorities) {
		        grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority());
            }
            grantedAuthoritiesAsString.append(" )");
		    LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString);
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(token);

        User user = User.get(token.getName());
        // Store the list of groups in a OicUserProperty so it can be retrieved later for the UserDetails object.
        user.addProperty(new OicUserProperty(userName, grantedAuthorities));

        if(emailFieldName!=null) {
	        String email = userInfo == null ? getField(idToken, emailFieldName) : (String) getField(userInfo, emailFieldName);
	        if (email != null) {
	            user.addProperty(new Mailer.UserProperty(email));
	        }
        }

        if(fullNameFieldName!=null) {
		    String fullName = userInfo == null ? getField(idToken, fullNameFieldName) : (String) getField(userInfo, fullNameFieldName);
		    if (fullName != null) {
		        user.setFullName(fullName);
		    }
        }

        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);

        return token;
    }
 
Example #8
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private boolean failedCheckOfTokenField(IdToken idToken) {
    if(tokenFieldToCheckKey == null || tokenFieldToCheckValue == null) {
        return false;
    }

    Object value = getField(idToken.getPayload(), tokenFieldToCheckKey);
    if(value == null) {
        return true;
    }

    return !tokenFieldToCheckValue.equals(String.valueOf(value));
}
 
Example #9
Source File: FirebaseTestTrampoline.java    From curiostack with MIT License 5 votes vote down vote up
public static FirebaseToken parseToken(JsonFactory jsonFactory, String tokenString) {
  try {
    return new FirebaseToken(IdToken.parse(jsonFactory, tokenString).getPayload());
  } catch (IOException e) {
    throw new UncheckedIOException("Could not parse firebase token.", e);
  }
}
 
Example #10
Source File: FirebaseTokenTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFirebaseTokenFromMinimalIdToken() {
  IdToken.Payload payload = new IdToken.Payload()
      .setSubject("testUser");

  FirebaseToken firebaseToken = new FirebaseToken(payload);

  assertEquals("testUser", firebaseToken.getUid());
  assertNull(firebaseToken.getIssuer());
  assertNull(firebaseToken.getEmail());
  assertFalse(firebaseToken.isEmailVerified());
  assertNull(firebaseToken.getName());
  assertNull(firebaseToken.getPicture());
  assertEquals(1, firebaseToken.getClaims().size());
}
 
Example #11
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private boolean containsLegacyUidField(IdToken.Payload payload) {
  Object dataField = payload.get("d");
  if (dataField instanceof ArrayMap) {
    return ((ArrayMap) dataField).get("uid") != null;
  }
  return false;
}
 
Example #12
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private String getErrorForTokenWithoutKid(IdToken.Header header, IdToken.Payload payload) {
  if (isCustomToken(payload)) {
    return String.format("%s expects %s, but was given a custom token.",
        method, articledShortName);
  } else if (isLegacyCustomToken(header, payload)) {
    return String.format("%s expects %s, but was given a legacy custom token.",
        method, articledShortName);
  }
  return String.format("Firebase %s has no \"kid\" claim.", shortName);
}
 
Example #13
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the cryptographic signature on the FirebaseToken. Can block on a web request to fetch
 * the keys if they have expired.
 */
private boolean isSignatureValid(IdToken token) throws GeneralSecurityException, IOException {
  for (PublicKey key : publicKeysManager.getPublicKeys()) {
    if (token.verifySignature(key)) {
      return true;
    }
  }
  return false;
}
 
Example #14
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void checkSignature(IdToken token) throws FirebaseAuthException {
  try {
    if (!isSignatureValid(token)) {
      throw new FirebaseAuthException(ERROR_INVALID_CREDENTIAL,
          String.format(
              "Failed to verify the signature of Firebase %s. %s",
              shortName,
              getVerifyTokenMessage()));
    }
  } catch (GeneralSecurityException | IOException e) {
    throw new FirebaseAuthException(
        ERROR_RUNTIME_EXCEPTION, "Error while verifying signature.", e);
  }
}
 
Example #15
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private void checkContents(final IdToken token) throws FirebaseAuthException {
  String errorMessage = getErrorIfContentInvalid(token);
  if (errorMessage != null) {
    String detailedError = String.format("%s %s", errorMessage, getVerifyTokenMessage());
    throw new FirebaseAuthException(ERROR_INVALID_CREDENTIAL, detailedError);
  }
}
 
Example #16
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private IdToken parse(String token) throws FirebaseAuthException {
  try {
    return IdToken.parse(jsonFactory, token);
  } catch (IllegalArgumentException | IOException e) {
    // Old versions of guava throw an IOException for invalid strings, while new versions
    // might throw an IllegalArgumentException
    String detailedError = String.format(
        "Failed to parse Firebase %s. Make sure you passed a string that represents a complete "
            + "and valid JWT. See %s for details on how to retrieve %s.",
        shortName,
        docUrl,
        articledShortName);
    throw new FirebaseAuthException(ERROR_INVALID_CREDENTIAL, detailedError, e);
  }
}
 
Example #17
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private boolean isLegacyCustomToken(IdToken.Header header, IdToken.Payload payload) {
  return "HS256".equals(header.getAlgorithm())
      && new BigDecimal(0).equals(payload.get("v"))
      && containsLegacyUidField(payload);
}
 
Example #18
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private boolean isCustomToken(IdToken.Payload payload) {
  return FIREBASE_AUDIENCE.equals(payload.getAudience());
}
 
Example #19
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private boolean verifyTimestamps(IdToken token) {
  long currentTimeMillis = idTokenVerifier.getClock().currentTimeMillis();
  return token.verifyTime(currentTimeMillis, idTokenVerifier.getAcceptableTimeSkewSeconds());
}
 
Example #20
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
/**
 * Handles the the securityRealm/commenceLogin resource and sends the user off to the IdP
 * @param from the relative URL to the page that the user has just come from
 * @param referer the HTTP referer header (where to redirect the user back to after login has finished)
 * @return an {@link HttpResponse} object
*/
public HttpResponse doCommenceLogin(@QueryParameter String from, @Header("Referer") final String referer) {
    final String redirectOnFinish = determineRedirectTarget(from, referer);

    final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(
            BearerToken.queryParameterAccessMethod(),
            httpTransport,
            JSON_FACTORY,
            new GenericUrl(tokenServerUrl),
            new ClientParametersAuthentication(
                    clientId,
                    clientSecret.getPlainText()
            ),
            clientId,
            authorizationServerUrl
    )
        .setScopes(Arrays.asList(scopes))
        .build();

    return new OicSession(flow, from, buildOAuthRedirectUrl()) {
        @Override
        public HttpResponse onSuccess(String authorizationCode) {
            try {
                AuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(authorizationCode)
                    .setRedirectUri(buildOAuthRedirectUrl());
                // Supplying scope is not allowed when obtaining an access token with an authorization code.
                tokenRequest.setScopes(Collections.<String>emptyList());

                IdTokenResponse response = IdTokenResponse.execute(tokenRequest);

                this.setIdToken(response.getIdToken());

                IdToken idToken = IdToken.parse(JSON_FACTORY, response.getIdToken());

                Object username;
                GenericJson userInfo = null;
                if (Strings.isNullOrEmpty(userInfoServerUrl)) {
                    username = getField(idToken.getPayload(), userNameField);
                    if(username == null) {
                        return HttpResponses.error(500,"no field '" + userNameField + "' was supplied in the token payload to be used as the username");
                    }
                } else {
                    userInfo = getUserInfo(flow, response.getAccessToken());
                    username = getField(userInfo, userNameField);
                    if(username == null) {
                        return HttpResponses.error(500,"no field '" + userNameField + "' was supplied by the UserInfo payload to be used as the username");
                    }
                }

                if(failedCheckOfTokenField(idToken)) {
                    return HttpResponses.errorWithoutStack(401, "Unauthorized");
                }

                flow.createAndStoreCredential(response, null);

                loginAndSetUserData(username.toString(), idToken, userInfo);

                return new HttpRedirect(redirectOnFinish);

            } catch (IOException e) {
                return HttpResponses.error(500,e);
            }

        }
    }.doCommenceLogin();
}
 
Example #21
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
private String getErrorIfContentInvalid(final IdToken idToken) {
  final Header header = idToken.getHeader();
  final Payload payload = idToken.getPayload();

  String errorMessage = null;
  if (header.getKeyId() == null) {
    errorMessage = getErrorForTokenWithoutKid(header, payload);
  } else if (!RS256.equals(header.getAlgorithm())) {
    errorMessage = String.format(
        "Firebase %s has incorrect algorithm. Expected \"%s\" but got \"%s\".",
        shortName,
        RS256,
        header.getAlgorithm());
  } else if (!idToken.verifyAudience(idTokenVerifier.getAudience())) {
    errorMessage = String.format(
        "Firebase %s has incorrect \"aud\" (audience) claim. Expected \"%s\" but got \"%s\". %s",
        shortName,
        joinWithComma(idTokenVerifier.getAudience()),
        joinWithComma(payload.getAudienceAsList()),
        getProjectIdMatchMessage());
  } else if (!idToken.verifyIssuer(idTokenVerifier.getIssuers())) {
    errorMessage = String.format(
        "Firebase %s has incorrect \"iss\" (issuer) claim. Expected \"%s\" but got \"%s\". %s",
        shortName,
        joinWithComma(idTokenVerifier.getIssuers()),
        payload.getIssuer(),
        getProjectIdMatchMessage());
  } else if (payload.getSubject() == null) {
    errorMessage = String.format(
        "Firebase %s has no \"sub\" (subject) claim.",
        shortName);
  } else if (payload.getSubject().isEmpty()) {
    errorMessage = String.format(
        "Firebase %s has an empty string \"sub\" (subject) claim.",
        shortName);
  } else if (payload.getSubject().length() > 128) {
    errorMessage = String.format(
        "Firebase %s has \"sub\" (subject) claim longer than 128 characters.",
        shortName);
  } else if (!verifyTimestamps(idToken)) {
    errorMessage = String.format(
        "Firebase %s has expired or is not yet valid. Get a fresh %s and try again.",
        shortName,
        shortName);
  }

  return errorMessage;
}
 
Example #22
Source File: ConnectActivity.java    From android-java-connect-rest-sample with MIT License 4 votes vote down vote up
private void connect() {
    // define the post-auth callback
    AuthenticationCallback<String> callback =
            new AuthenticationCallback<String>() {

                @Override
                public void onSuccess(String idToken) {
                    String name = "";
                    String preferredUsername = "";
                    try {
                        // get the user info from the id token
                        IdToken claims = IdToken.parse(new GsonFactory(), idToken);
                        name = claims.getPayload().get("name").toString();
                        preferredUsername = claims.getPayload().get("preferred_username").toString();
                    } catch (IOException ioe) {
                        Log.e(TAG, ioe.getMessage());
                    } catch (NullPointerException npe) {
                        Log.e(TAG, npe.getMessage());

                    }

                    // Prepare the SendMailActivity intent
                    Intent sendMailActivity =
                            new Intent(ConnectActivity.this, SendMailActivity.class);

                    // take the user's info along
                    sendMailActivity.putExtra(SendMailActivity.ARG_GIVEN_NAME, name);
                    sendMailActivity.putExtra(SendMailActivity.ARG_DISPLAY_ID, preferredUsername);

                    // actually start the activity
                    startActivity(sendMailActivity);

                    resetUIForConnect();
                }

                @Override
                public void onError(Exception exc) {
                    showConnectErrorUI();
                }
            };

    AuthenticationManager mgr = AuthenticationManager.getInstance(this);
    mgr.connect(this, callback);
}
 
Example #23
Source File: FirebaseTokenVerifierImpl.java    From firebase-admin-java with Apache License 2.0 3 votes vote down vote up
/**
 * Verifies that the given token string is a valid Firebase JWT. This implementation considers
 * a token string to be valid if all the following conditions are met:
 * <ol>
 *   <li>The token string is a valid RS256 JWT.</li>
 *   <li>The JWT contains a valid key ID (kid) claim.</li>
 *   <li>The JWT is not expired, and it has been issued some time in the past.</li>
 *   <li>The JWT contains valid issuer (iss) and audience (aud) claims as determined by the
 *   {@code IdTokenVerifier}.</li>
 *   <li>The JWT contains a valid subject (sub) claim.</li>
 *   <li>The JWT is signed by a Firebase Auth backend server.</li>
 * </ol>
 *
 * @param token The token string to be verified.
 * @return A decoded representation of the input token string.
 * @throws FirebaseAuthException If the input token string does not meet any of the conditions
 *     listed above.
 */
@Override
public FirebaseToken verifyToken(String token) throws FirebaseAuthException {
  IdToken idToken = parse(token);
  checkContents(idToken);
  checkSignature(idToken);
  return new FirebaseToken(idToken.getPayload());
}