public static void setCustomUserClaims( String uid) throws InterruptedException, ExecutionException { // [START set_custom_user_claims] // Set admin privilege on the user corresponding to uid. Map<String, Object> claims = new HashMap<>(); claims.put("admin", true); FirebaseAuth.getInstance().setCustomUserClaimsAsync(uid, claims).get(); // The new custom claims will propagate to the user's ID token the // next time a new one is issued. // [END set_custom_user_claims] String idToken = "id_token"; // [START verify_custom_claims] // Verify the ID token first. FirebaseToken decoded = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get(); if (Boolean.TRUE.equals(decoded.getClaims().get("admin"))) { // Allow access to requested admin resource. } // [END verify_custom_claims] // [START read_custom_user_claims] // Lookup the user associated with the specified uid. UserRecord user = FirebaseAuth.getInstance().getUserAsync(uid).get(); System.out.println(user.getCustomClaims().get("admin")); // [END read_custom_user_claims] }
@Test public void verifyToken() throws Exception { FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), createPayload())); IdToken.Payload payload = (IdToken.Payload) token.getClaims(); assertTrue(payload.getAudienceAsList().contains(PROJECT_ID)); assertEquals(ISSUER, payload.getIssuer()); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_MissingKeyId() throws Exception { Header header = createHeader(); header.setKeyId(null); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(header, createPayload())); thrown.expectMessage("Firebase ID token has no \"kid\" claim."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_MissingKeyId_CustomToken() throws Exception { Header header = createHeader(); header.setKeyId(null); Payload payload = createPayload(); payload.setAudience( "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit" + ".v1.IdentityToolkit"); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken(FACTORY, createToken(header, payload)); thrown.expectMessage("verifyIdToken() expects an ID token, but was given a custom token."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_IncorrectAlgorithm() throws Exception { Header header = createHeader(); header.setAlgorithm("HS256"); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(header, createPayload())); thrown.expectMessage("Firebase ID token has incorrect algorithm."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_IncorrectAudience() throws Exception { Payload payload = createPayload(); payload.setAudience( "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1." + "IdentityToolkit"); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage("Firebase ID token has incorrect \"aud\" (audience) claim."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_IncorrectIssuer() throws Exception { Payload payload = createPayload(); payload.setIssuer("https://foobar.google.com/" + PROJECT_ID); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage("Firebase ID token has incorrect \"iss\" (issuer) claim."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_MissingSubject() throws Exception { Payload payload = createPayload(); payload.setSubject(null); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage("Firebase ID token has no \"sub\" (subject) claim."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_EmptySubject() throws Exception { Payload payload = createPayload(); payload.setSubject(""); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage("Firebase ID token has an empty string \"sub\" (subject) claim."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_LongSubject() throws Exception { Payload payload = createPayload(); payload.setSubject( "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv" + "wxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage( "Firebase ID token has \"sub\" (subject) claim longer than 128 characters."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_NotYetIssued() throws Exception { Payload payload = createPayload(); payload.setIssuedAtTimeSeconds(System.currentTimeMillis() / 1000); payload.setExpirationTimeSeconds(System.currentTimeMillis() / 1000 + 3600); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage("Firebase ID token has expired or is not yet valid."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_Expired() throws Exception { Payload payload = createPayload(); payload.setIssuedAtTimeSeconds(0L); payload.setExpirationTimeSeconds(3600L); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), payload)); thrown.expectMessage("Firebase ID token has expired or is not yet valid."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenFailure_WrongCert() throws Exception { initCrypto(ServiceAccount.OWNER.getPrivateKey(), ServiceAccount.NONE.getCert()); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), createPayload())); thrown.expectMessage("Firebase ID token isn't signed by a valid public key."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Test public void verifyTokenCertificateError() throws Exception { FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken( FACTORY, createToken(createHeader(), createPayload())); MockHttpTransport mockTransport = new MockHttpTransport() { @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { throw new IOException("Expected error"); } }; FirebaseTokenVerifier verifier = new FirebaseTokenVerifier.Builder() .setClock(CLOCK) .setPublicKeysManager( new GooglePublicKeysManager.Builder(mockTransport, FACTORY) .setClock(CLOCK) .setPublicCertsEncodedUrl(FirebaseTokenVerifier.CLIENT_CERT_URL) .build()) .setProjectId(PROJECT_ID) .build(); try { verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); Assert.fail("No exception thrown"); } catch (FirebaseAuthException expected) { assertTrue(expected.getCause() instanceof IOException); assertEquals("Expected error", expected.getCause().getMessage()); } }
@Test public void legacyCustomToken() throws Exception { initCrypto(ServiceAccount.OWNER.getPrivateKey(), ServiceAccount.NONE.getCert()); FirebaseToken token = TestOnlyImplFirebaseAuthTrampolines.parseToken(FACTORY, LEGACY_CUSTOM_TOKEN); thrown.expectMessage( "verifyIdToken() expects an ID token, but was given a legacy custom token."); verifier.verifyTokenAndSignature(TestOnlyImplFirebaseAuthTrampolines.getToken(token)); }
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { final FirebaseAuthenticationToken authenticationToken = (FirebaseAuthenticationToken) authentication; final CompletableFuture<FirebaseToken> future = new CompletableFuture<>(); firebaseAuth.verifyIdToken(authenticationToken.getToken()).addOnSuccessListener(future::complete); try { final FirebaseToken token = future.get(); return new FirebaseUserDetails(token.getEmail(), token.getUid()); } catch (InterruptedException | ExecutionException e) { throw new SessionAuthenticationException(e.getMessage()); } }
private Boolean validateToken(String token) { Task task = FirebaseAuth.getInstance().verifyIdToken(token); // TODO refactor // wait for task to finish while (!task.isComplete()) { } FirebaseToken decodedToken = (FirebaseToken) task.getResult(); return decodedToken.getUid() != null && !decodedToken.getUid().isEmpty(); }
public static void verifyIdToken(String idToken) throws InterruptedException, ExecutionException { // [START verify_id_token] // idToken comes from the client app (shown above) FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken).get(); String uid = decodedToken.getUid(); // [END verify_id_token] System.out.println("Decoded ID token from user: " + uid); }
public static final void saveAccount(FirebaseToken firebaseToken, String token) { AccountJDO account = AccountManager.addAccount( firebaseToken.getUid(), AccountJDO.FIREBASECLIENT, firebaseToken.getEmail(), firebaseToken.getName(), firebaseToken.getIssuer(), firebaseToken.getName(), firebaseToken.getPicture(), false); UserLoggedInManager.submitOauthUser(account.getUniqueId(), token); }
public void authenticateFirebaseUser(String userToken) { Task<FirebaseToken> tokenTask = FirebaseAuth.getInstance().verifyIdToken(userToken); try { Tasks.await(tokenTask); } catch (Exception e) { LOG.log(Level.SEVERE, "An error occurred while authenticating the user token", e); return; } this.user = tokenTask.getResult(); }
/** Parses a serialized {@link FirebaseToken} without verification. */ public static FirebaseToken parse(String serialized) { return FirebaseTestTrampoline.parseToken(JacksonFactory.getDefaultInstance(), serialized); }