com.google.firebase.auth.FirebaseToken Java Examples
The following examples show how to use
com.google.firebase.auth.FirebaseToken.
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: FirebaseAccountMergeService.java From zhcet-web with Apache License 2.0 | 6 votes |
/** * Merges firebase data into user account * * - Saves token claims in database * - Merges email and verification status from token * - Updates profile picture from provider data * * Mail merge and avatar update is done only if the user account information is not already present * @param userAuth User Account the data is to be merged in * @param token Decoded Firebase Token containing data */ @Async public void mergeFirebaseDetails(@Nullable UserAuth userAuth, @Nullable FirebaseToken token) { if (userAuth == null || token == null || !firebaseService.canProceed()) return; Optional<User> optionalUser = userService.findById(userAuth.getUsername()); if (!optionalUser.isPresent()) return; User user = optionalUser.get(); if (token.getClaims() != null) user.getDetails().setFirebaseClaims(token.getClaims().toString()); mergeMail(user, token); if (Strings.isNullOrEmpty(user.getDetails().getAvatarUrl()) && !Strings.isNullOrEmpty(token.getPicture())) { user.getDetails().setOriginalAvatarUrl(token.getPicture()); user.getDetails().setAvatarUrl(token.getPicture()); AuthManager.updateAvatar(userAuth, user.getDetails().getAvatarUrl()); } userService.save(user); }
Example #2
Source File: AuthSnippets.java From quickstart-java with Apache License 2.0 | 6 votes |
public static void verifyIdTokenCheckRevoked(String idToken) throws InterruptedException, ExecutionException { // [START verify_id_token_check_revoked] try { // Verify the ID token while checking if the token is revoked by passing checkRevoked // as true. boolean checkRevoked = true; FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdTokenAsync(idToken, checkRevoked).get(); // Token is valid and not revoked. String uid = decodedToken.getUid(); } catch (ExecutionException e) { if (e.getCause() instanceof FirebaseAuthException) { FirebaseAuthException authError = (FirebaseAuthException) e.getCause(); if (authError.getErrorCode().equals("id-token-revoked")) { // Token has been revoked. Inform the user to reauthenticate or signOut() the user. } else { // Token is invalid. } } } // [END verify_id_token_check_revoked] }
Example #3
Source File: AuthSnippets.java From quickstart-java with Apache License 2.0 | 6 votes |
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] }
Example #4
Source File: FirebaseAuthenticationProvider.java From zhcet-web with Apache License 2.0 | 6 votes |
private UserDetails retrieveUser(FirebaseToken decodedToken) { String username = decodedToken.getUid(); if (Strings.isNullOrEmpty(username)) return null; UserDetails user = userDetailsService.loadUserByUsername(username); if (user != null) return user; if (Strings.isNullOrEmpty(decodedToken.getEmail())) return null; if (!decodedToken.isEmailVerified()) log.warn("Unverified Email Login {}", decodedToken.getEmail()); return userDetailsService.loadUserByUsername(decodedToken.getEmail()); }
Example #5
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 6 votes |
public Response checkPermissions(String sessionCookie) { // [START session_verify_with_permission_check] try { final boolean checkRevoked = true; FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie( sessionCookie, checkRevoked); if (Boolean.TRUE.equals(decodedToken.getClaims().get("admin"))) { return serveContentForAdmin(decodedToken); } return Response.status(Status.UNAUTHORIZED).entity("Insufficient permissions").build(); } catch (FirebaseAuthException e) { // Session cookie is unavailable, invalid or revoked. Force user to login. return Response.temporaryRedirect(URI.create("/login")).build(); } // [END session_verify_with_permission_check] }
Example #6
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@POST @Path("/profile") public Response verifySessionCookie(@CookieParam("session") Cookie cookie) { String sessionCookie = cookie.getValue(); try { // Verify the session cookie. In this case an additional check is added to detect // if the user's Firebase session was revoked, user deleted/disabled, etc. final boolean checkRevoked = true; FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie( sessionCookie, checkRevoked); return serveContentForUser(decodedToken); } catch (FirebaseAuthException e) { // Session cookie is unavailable, invalid or revoked. Force user to login. return Response.temporaryRedirect(URI.create("/login")).build(); } }
Example #7
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 6 votes |
public Response checkAuthTime(String idToken) throws FirebaseAuthException { // [START check_auth_time] // To ensure that cookies are set only on recently signed in users, check auth_time in // ID token before creating a cookie. FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken); long authTimeMillis = TimeUnit.SECONDS.toMillis( (long) decodedToken.getClaims().get("auth_time")); // Only process if the user signed in within the last 5 minutes. if (System.currentTimeMillis() - authTimeMillis < TimeUnit.MINUTES.toMillis(5)) { long expiresIn = TimeUnit.DAYS.toMillis(5); SessionCookieOptions options = SessionCookieOptions.builder() .setExpiresIn(expiresIn) .build(); String sessionCookie = FirebaseAuth.getInstance().createSessionCookie(idToken, options); // Set cookie policy parameters as required. NewCookie cookie = new NewCookie("session", sessionCookie); return Response.ok().cookie(cookie).build(); } // User did not sign in recently. To guard against ID token theft, require // re-authentication. return Response.status(Status.UNAUTHORIZED).entity("Recent sign in required").build(); // [END check_auth_time] }
Example #8
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 6 votes |
public static void verifyIdTokenCheckRevoked(String idToken) { // [START verify_id_token_check_revoked] try { // Verify the ID token while checking if the token is revoked by passing checkRevoked // as true. boolean checkRevoked = true; FirebaseToken decodedToken = FirebaseAuth.getInstance() .verifyIdToken(idToken, checkRevoked); // Token is valid and not revoked. String uid = decodedToken.getUid(); } catch (FirebaseAuthException e) { if (e.getErrorCode().equals("id-token-revoked")) { // Token has been revoked. Inform the user to re-authenticate or signOut() the user. } else { // Token is invalid. } } // [END verify_id_token_check_revoked] }
Example #9
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 6 votes |
public static void setCustomUserClaims( String uid) throws FirebaseAuthException { // [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().setCustomUserClaims(uid, claims); // 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().verifyIdToken(idToken); 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().getUser(uid); System.out.println(user.getCustomClaims().get("admin")); // [END read_custom_user_claims] }
Example #10
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 5 votes |
@POST @Path("/sessionLogout") public Response clearSessionCookieAndRevoke(@CookieParam("session") Cookie cookie) { String sessionCookie = cookie.getValue(); try { FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(sessionCookie); FirebaseAuth.getInstance().revokeRefreshTokens(decodedToken.getUid()); final int maxAge = 0; NewCookie newCookie = new NewCookie(cookie, null, maxAge, true); return Response.temporaryRedirect(URI.create("/login")).cookie(newCookie).build(); } catch (FirebaseAuthException e) { return Response.temporaryRedirect(URI.create("/login")).build(); } }
Example #11
Source File: AuthLinkService.java From zhcet-web with Apache License 2.0 | 5 votes |
/** * Links authenticated user to one of the Identity providers, like Google * Also merges the provider data like email, verification status, and photo into user account * NOTE: Only to be called from an authenticated endpoint * @param token String: Firebase Authentication Token */ public void linkAccount(UserAuth userAuth, String token) { if (!firebaseService.canProceed()) return; try { FirebaseToken decodedToken = FirebaseService.getToken(token); log.info(decodedToken.getClaims().toString()); firebaseAccountMergeService.mergeFirebaseDetails(userAuth, decodedToken); } catch (ExecutionException | InterruptedException e) { log.error("Error linking data", e); } }
Example #12
Source File: ServerAuthInterceptor.java From startup-os with Apache License 2.0 | 5 votes |
@Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall( ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) { String token = metadata.get(Metadata.Key.of("token", ASCII_STRING_MARSHALLER)); System.out.println("Token: " + token); boolean tokenIsValid = false; try { FirebaseToken firebaseToken = FirebaseAuth.getInstance().verifyIdToken(token); System.err.println("Email for token: " + firebaseToken.getEmail()); // TODO: properly validate whether user has rights //noinspection ConstantConditions if (true) { tokenIsValid = true; } } catch (Exception e) { e.printStackTrace(); System.err.println("Was unable to parse token"); } if (!tokenIsValid) { serverCall.close(Status.UNAUTHENTICATED, metadata); return new ServerCall.Listener<ReqT>() {}; } else { return serverCallHandler.startCall(serverCall, metadata); } }
Example #13
Source File: FirebaseAuthenticationProvider.java From zhcet-web with Apache License 2.0 | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!firebaseService.canProceed()) return null; // Firebase is disabled, so we cannot proceed String token = authentication.getCredentials().toString(); if (Strings.isNullOrEmpty(token)) return null; // Cannot parse empty token try { FirebaseToken decodedToken = FirebaseService.getToken(token); log.debug("User Claims: {}", decodedToken.getClaims()); UserDetails user = retrieveUser(decodedToken); if (user == null) throwBadCredentialsException(); userDetailsChecker.check(user); if (user instanceof UserAuth) { firebaseAccountMergeService.mergeFirebaseDetails((UserAuth) user, decodedToken); } else { log.warn("User {} is not of UserAuth Type", user); } return createSuccessAuthentication(user, authentication); } catch (InterruptedException | ExecutionException e) { log.warn("Unable to decode Firebase token"); throwBadCredentialsException(); } catch (UsernameNotFoundException une) { throwBadCredentialsException(); } return null; }
Example #14
Source File: FirebaseAuthenticationProvider.java From spring-security-firebase with MIT License | 5 votes |
@Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { final FirebaseAuthenticationToken authenticationToken = (FirebaseAuthenticationToken) authentication; ApiFuture<FirebaseToken> task = firebaseAuth.verifyIdTokenAsync(authenticationToken.getToken()); try { FirebaseToken token = task.get(); return new FirebaseUserDetails(token.getEmail(), token.getUid()); } catch (InterruptedException | ExecutionException e) { throw new SessionAuthenticationException(e.getMessage()); } }
Example #15
Source File: FirebaseAuthorizer.java From curiostack with MIT License | 5 votes |
@Override public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) { CompletableFuture<Boolean> result = new CompletableFuture<>(); ApiFutures.addCallback( firebaseAuth.verifyIdTokenAsync(data.accessToken()), new ApiFutureCallback<FirebaseToken>() { @Override public void onFailure(Throwable t) { result.complete(false); } @Override public void onSuccess(FirebaseToken token) { if (!token.isEmailVerified() && !config.isAllowUnverifiedEmail()) { result.complete(false); return; } if (!config.getAllowedGoogleDomains().isEmpty()) { @SuppressWarnings("unchecked") Map<String, Object> firebaseClaims = (Map<String, Object>) token.getClaims().get("firebase"); if (!firebaseClaims.get("sign_in_provider").equals("google.com") || !config.getAllowedGoogleDomains().contains(getEmailDomain(token.getEmail()))) { result.complete(false); return; } } ctx.setAttr(FIREBASE_TOKEN, token); ctx.setAttr(RAW_FIREBASE_TOKEN, data.accessToken()); result.complete(true); } }, MoreExecutors.directExecutor()); return result; }
Example #16
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 5 votes |
public static void verifyIdToken(String idToken) throws FirebaseAuthException { // [START verify_id_token] // idToken comes from the client app (shown above) FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken); String uid = decodedToken.getUid(); // [END verify_id_token] System.out.println("Decoded ID token from user: " + uid); }
Example #17
Source File: AuthSnippets.java From quickstart-java with Apache License 2.0 | 5 votes |
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); }
Example #18
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 4 votes |
private Response serveContentForAdmin(FirebaseToken decodedToken) { return null; }
Example #19
Source File: FirebaseAuthSnippets.java From firebase-admin-java with Apache License 2.0 | 4 votes |
private Response serveContentForUser(FirebaseToken decodedToken) { return null; }
Example #20
Source File: FirebaseAccountMergeService.java From zhcet-web with Apache License 2.0 | 4 votes |
/** * Merges mail from firebase token into user account * * - If the email of user is already verified, process is skipped * - If the email in provider is already claimed by another user, that user's email * and it's verification status is cleared and given to the passed in user. * Previous user is notified of this revocation * - If the provider email is not verified, but account email is null, provider email is saved. * But verification status is set to false * @param user User * @param token Firebase Token containing email information */ private void mergeMail(User user, FirebaseToken token) { if (Strings.isNullOrEmpty(token.getEmail())) return; Optional<User> duplicate = userService.getUserByEmail(token.getEmail()); // Exchange user emails if someone else has access to the email provided if (duplicate.isPresent() && !duplicate.get().getUserId().equals(user.getUserId())) { User duplicateUser = duplicate.get(); log.warn("Another user account with same email exists, {} {} : {}", user.getUserId(), duplicateUser.getUserId(), token.getEmail()); if (token.isEmailVerified()) { log.warn("New user has verified email, unconditionally exchanging emails from previous user"); if (duplicateUser.isEmailVerified()) eventPublisher.publishEvent(new EmailVerifiedEvent(duplicateUser, false)); duplicateUser.setEmail(null); duplicateUser.setEmailVerified(false); userService.save(duplicateUser); userService.findById(duplicateUser.getUserId()).ifPresent(dupe -> { log.info("Cleared email info from duplicate user, {}", dupe.getEmail()); }); eventPublisher.publishEvent(new DuplicateEmailEvent(user, duplicateUser, token.getEmail())); } } if (user.isEmailVerified() && user.getEmail() != null && !user.getEmail().equals(token.getEmail())) { log.debug("User email is already verified, skipping mail merge"); return; } if (token.isEmailVerified()) { user.setEmail(token.getEmail()); user.setEmailVerified(true); } else if (Strings.isNullOrEmpty(user.getEmail())) { user.setEmail(token.getEmail()); user.setEmailVerified(false); } }
Example #21
Source File: FirebaseService.java From zhcet-web with Apache License 2.0 | 4 votes |
public static FirebaseToken getToken(String token) throws ExecutionException, InterruptedException { return FirebaseAuth.getInstance().verifyIdTokenAsync(token).get(); }
Example #22
Source File: FirebaseTestUtil.java From curiostack with MIT License | 4 votes |
/** Parses a serialized {@link FirebaseToken} without verification. */ public static FirebaseToken parse(String serialized) { return FirebaseTestTrampoline.parseToken(JacksonFactory.getDefaultInstance(), serialized); }