简体   繁体   中英

firebase-server-sdk verify token server side java.lang.IllegalStateException: Task is not yet complete

I'm having trouble using the firebase-server-sdk with java, and verifying tokens server side. I have a rest controller setup to take a token from a client, then I run the following code.

FirebaseAuthVerifier.java

@Service
public class FirebaseAuthVerifier implements AuthVerifier {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public boolean verify(AuthToken token) throws GeneralSecurityException, IOException {
        Task<FirebaseToken> fbTask = FirebaseAuth.getInstance().verifyIdToken(token.getTokenId());

        fbTask.getResult();

        return fbTask.isSuccessful();
    }

}

FirebaseAuthController

@RestController
@RequestMapping("/api/firebase/auth")
public class FirebaseAuthController {

    @Autowired
    private FirebaseAuthVerifier glAuthVerifier;

    @ResponseBody
    @CrossOrigin(origins = "http://localhost:3000")
    @RequestMapping(value = "/verify", method = RequestMethod.POST, headers = "Content-Type=application/json", consumes = "application/json", produces = "application/json")
    public ResponseEntity<AuthTokenVerification> verify(@RequestBody GoogleAuthToken glAuthToken) throws GeneralSecurityException, IOException {
        // init return
        AuthTokenVerification glAuthTokenVerification = new GoogleAuthTokenVerification();

        // verify token
        boolean isVerified = this.glAuthVerifier.verify(glAuthToken);
        glAuthTokenVerification.setIsVerified(isVerified);

        // return json response
        ResponseEntity<AuthTokenVerification> response = new ResponseEntity<>(glAuthTokenVerification, HttpStatus.OK);
        return response;
    }

}

but I receive an exception

java.lang.IllegalStateException: Task is not yet complete

I'm trying to do something simple here, but I'm not sure how to have java wait for completion here.

Using custom jwt id token validation.

@Service
public class FirebaseAuthVerifier implements AuthVerifier {

    private static final Logger logger = LoggerFactory.getLogger(FirebaseAuthVerifier.class);
    private static final String pubKeyUrl = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com";

    /**
     *
     * @param token
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    public boolean verify(AuthToken token) throws GeneralSecurityException, IOException {
        // get public keys
        JsonObject publicKeys = getPublicKeysJson();

        // verify count
        int size = publicKeys.entrySet().size();
        int count = 0;

        // get json object as map
        // loop map of keys finding one that verifies
        for (Map.Entry<String, JsonElement> entry: publicKeys.entrySet()) {
            // log
            logger.info("attempting jwt id token validation with: ");

            try {
                // trying next key
                count++;

                // get public key
                PublicKey publicKey = getPublicKey(entry);

                // validate claim set
                Jwts.parser().setSigningKey(publicKey).parse(token.getTokenId());

                // success, we can return
                return true;
            } catch(Exception e) {
                // log
                logger.info("Firebase id token verification error: ");
                logger.info(e.getMessage());
                // claims may have been tampered with
                // if this is the last key, return false
                if (count == size) {
                    return false;
                }
            }
        }

        // no jwt exceptions
        return true;
    }

    /**
     *
     * @param entry
     * @return
     * @throws GeneralSecurityException
     */
    private PublicKey getPublicKey(Map.Entry<String, JsonElement> entry) throws GeneralSecurityException, IOException {
        String publicKeyPem = entry.getValue().getAsString()
                .replaceAll("-----BEGIN (.*)-----", "")
                .replaceAll("-----END (.*)----", "")
                .replaceAll("\r\n", "")
                .replaceAll("\n", "")
                .trim();

        logger.info(publicKeyPem);

        // generate x509 cert
        InputStream inputStream = new ByteArrayInputStream(entry.getValue().getAsString().getBytes("UTF-8"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate)cf.generateCertificate(inputStream);

        return cert.getPublicKey();
    }

    /**
     *
     * @return
     * @throws IOException
     */
    private JsonObject getPublicKeysJson() throws IOException {
        // get public keys
        URI uri = URI.create(pubKeyUrl);
        GenericUrl url = new GenericUrl(uri);
        HttpTransport http = new NetHttpTransport();
        HttpResponse response = http.createRequestFactory().buildGetRequest(url).execute();

        // store json from request
        String json = response.parseAsString();
        // disconnect
        response.disconnect();

        // parse json to object
        JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

        return jsonObject;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM