Forked from janakagamini/FirebaseUserIdTokenInterceptor.java
Created
October 8, 2020 18:29
-
-
Save mario1987/2765197188e893e25757b4b9a97e8a56 to your computer and use it in GitHub Desktop.
A simple Interceptor to include a Firebase user's id token in all requests. Useful for authenticating Firebase users with a custom backend. See: https://firebase.google.com/docs/auth/admin/verify-id-tokens#retrieve_id_tokens_on_clients)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class FirebaseUserIdTokenInterceptor implements Interceptor { | |
| // Custom header for passing ID token in request. | |
| private static final String X_FIREBASE_ID_TOKEN = "YOUR-CUSTOM-HEADER"; | |
| @Override | |
| public Response intercept(Chain chain) throws IOException { | |
| Request request = chain.request(); | |
| try { | |
| FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); | |
| if (user == null) { | |
| throw new Exception("User is not logged in."); | |
| } else { | |
| Task<GetTokenResult> task = user.getToken(true); | |
| GetTokenResult tokenResult = Tasks.await(task); | |
| String idToken = tokenResult.getToken(); | |
| if (idToken == null) { | |
| throw new Exception("idToken is null"); | |
| } else { | |
| Request modifiedRequest = request.newBuilder() | |
| .addHeader(X_FIREBASE_ID_TOKEN, idToken) | |
| .build(); | |
| return chain.proceed(modifiedRequest); | |
| } | |
| } | |
| } catch (Exception e) { | |
| throw new IOException(e.getMessage()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment