Integrate firebase auth with google app engine cloud endpoints

后端 未结 2 496
没有蜡笔的小新
没有蜡笔的小新 2021-02-03 12:27

Can someone specify (with some sample code) how to verify the firebase token in an google cloud endpoint? The recently asked question does not clarifiy it at all (How to integra

2条回答
  •  耶瑟儿~
    2021-02-03 13:18

    You can use a CustomAuthenticator:

    public class CustomAuthenticator implements Authenticator {
        private static final Logger LOG = Logger.getLogger(CustomAuthenticator.class.getName());
        private static final String COOKIE_FIREBASE_TOKEN = "firebase_token";
    
        static {
            LOG.info("CustomAuthenticator: initializing");
            InputStream serviceAccountResourceStream = CustomAuthenticator.class.getResourceAsStream("/serviceAccountKey.json");
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setServiceAccount(serviceAccountResourceStream)
                    .build();
    
            FirebaseApp.initializeApp(options);
            LOG.info("CustomAuthenticator: initialized");
        }
    
        @Override
        public User authenticate(HttpServletRequest httpServletRequest) {
            User user = null;
            if (httpServletRequest.getCookies() != null) {
                for (Cookie cookie : httpServletRequest.getCookies()) {
                    if (cookie.getName().equals(COOKIE_FIREBASE_TOKEN)) {
                        FirebaseToken firebaseToken = FirebaseAuth.getInstance().verifyIdToken(cookie.getValue()).getResult();
                        user = new User(firebaseToken.getUid(), firebaseToken.getEmail());
                    }
                }
            }
            return user;
        }
    }
    

    In your API implementation, don't forget to enable your custom authenticator:

    @Api(name = "exampleWithAuth",
            version = "v1",
            ...
            auth = @ApiAuth(allowCookieAuth = AnnotationBoolean.TRUE), // This is needed to process your cookie for the token
            authenticators = {CustomAuthenticator.class} // Declare your custom authenticator
    )
    public class ExampleWithAuthEndpoint {
    
        @ApiMethod(httpMethod = "GET", path = "example")
        public Example getExample(User user /* Add User to enable API authentication */) {
            if (user != null) {
                // Do something
            }
            return null;
        }
    }
    

    Now when you call your API, just add the cookie firebase_token to your request.

    I hope this will help.

提交回复
热议问题