我在使用firebase-server-sdk和java时遇到问题,并验证令牌服务器端。我有一个休息控制器设置来从客户端获取令牌,然后我运行以下代码。
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;
}
}
但是我收到了一个例外
java.lang.IllegalStateException: Task is not yet complete
我试图在这里做一些简单的事情,但我不确定如何让java等待完成。
答案 0 :(得分:0)
使用自定义jwt id令牌验证。
@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;
}
}