I am working in a project, which needs to be logged in with google. Where I use a servlet to authenticate the user. In my servlet , I am getting the error Cannot instantiate the type JsonFactory.
Here is my code:
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
public class IdTokenVerifierAndParser {
private static final String GOOGLE_CLIENT_ID = "_id_";
public static GoogleIdToken.Payload getPayload (String tokenString) throws Exception {
JsonFactory jacksonFactory = new JsonFactory();
GoogleIdTokenVerifier googleIdTokenVerifier = new GoogleIdTokenVerifier(new NetHttpTransport(), jacksonFactory);
GoogleIdToken token = GoogleIdToken.parse(jacksonFactory, tokenString);
if (googleIdTokenVerifier.verify(token)) {
GoogleIdToken.Payload payload = token.getPayload();
if (!GOOGLE_CLIENT_ID.equals(payload.getAudience())) {
throw new IllegalArgumentException("Audience mismatch");
} else if (!GOOGLE_CLIENT_ID.equals(payload.getAuthorizedParty())) {
throw new IllegalArgumentException("Client ID mismatch");
}
return payload;
} else {
throw new IllegalArgumentException("id token cannot be verified");
}
}
}
CodePudding user response:
JsonFactory
is an abstract class. Abstract classes in Java can't be instantiated. You need to instantiate some concrete class that extends it.
Also, by the variable name jacksonFactory
I assume you wanted to use the Jackson implementation of this factory. It's marked as deprecated in the documentation, with the recommendation to use GsonFactory
implementation instead.
import com.google.api.client.json.gson.GsonFactory;
...
JsonFactory gsonFactory = new GsonFactory();