How to use Firebase with Spring boot REST Application?

dickyj picture dickyj · Aug 27, 2016 · Viewed 59.6k times · Source

I have a Spring Boot REST application that depends on the authentication done in Firebase.

On the client side Firebase generates a token whereby in the Spring Boot, I need to verify the UID.

But the code is in a callback mode, so how do I implement the function so that it can finish the task?

@RequestMapping(value = "/api/restCall", method = RequestMethod.POST, 
             consumes = "application/json", produces = "application/json")
public Object restCall(@RequestBody Parameters requestBody) throws Exception {
    String idToken = requestBody.getToken();
    Task<FirebaseToken> task = FirebaseAuth.getInstance().verifyIdToken(idToken)
            .addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {
            @Override
                public void onSuccess(FirebaseToken decodedToken) {
                    String uid = decodedToken.getUid();
                }
            });
    return "???"; // what return here?
}

How do I return after onSuccess? DeferredResult?

Answer

Maheshwar Ligade picture Maheshwar Ligade · Apr 7, 2017

To integrate Firebase with Spring, below is the sample code

In new Admin SDK the process is simple just use below code snippet.

FirebaseAuth.getInstance().deleteUser(uid);
System.out.println("Successfully deleted user.");

For more detail visit this URL https://firebase.google.com/docs/auth/admin/manage-users

This is for a legacy code. First add Firbase dependency

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-server-sdk</artifactId>
    <version>3.0.1</version>
</dependency>

Sample Code

@Component
public class FirebaseAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier(value = UserServiceImpl.NAME)
    private UserDetailsService userService;

    public boolean supports(Class<?> authentication) {
        return (FirebaseAuthenticationToken.class.isAssignableFrom(authentication));
    }

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (!supports(authentication.getClass())) {
            return null;
        }

        FirebaseAuthenticationToken authenticationToken = (FirebaseAuthenticationToken) authentication;
        UserDetails details = userService.loadUserByUsername(authenticationToken.getName());
        if (details == null) {
            throw new FirebaseUserNotExistsException();
        }

        authenticationToken = new FirebaseAuthenticationToken(details, authentication.getCredentials(),
                details.getAuthorities());

        return authenticationToken;
    }

}

For Complete example please gone through github below link https://github.com/savicprvoslav/Spring-Boot-starter Complete BlogPost with CRUD operation: https://medium.com/techwasti/spring-boot-firebase-crud-b0afab27b26e