我正在将 Google 注册/登录添加到我的网络应用程序,但我遇到了问题。
这是我的代码:
private static final HttpTransport transport = new NetHttpTransport();
private static final JsonFactory jsonFactory = new JacksonFactory();
private static final String MY_APP_GOOGLE_CLIENT_ID = "wouldntyouliketoknow";
public UsernamePasswordAuthenticationToken verify(final String idTokenString){
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setAudience(Collections.singletonList(MY_APP_GOOGLE_CLIENT_ID))
.build();
try {
GoogleIdToken idToken = verifier.verify(idTokenString);// <-- verifier.verify returns null !!!
if (idToken != null) {
Payload payload = idToken.getPayload();
String email = payload.getEmail();
if(Boolean.valueOf(payload.getEmailVerified())){
UserJPA jpa = userRepository.findByEmail(email);
if(jpa==null){
throw new UsernameNotFoundException("Cannot find user with email = "+email);
}
if(!jpa.isRegisterredWithGoogle()){
throw new UsernameNotFoundException("This user did not use the 'Register with google' option.");
}
bokiAuthenticationProvider.checkUserActiveAndUnlocked(jpa);
return new UsernamePasswordAuthenticationToken(jpa.getUsername(), jpa.getPasswordHesh(),
bokiAuthenticationProvider.getAuthorities(jpa.getUserHasRoleSecurityList()));
}
}else{
System.out.println("The *idToken* object is null !!!");
}
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
throw new MyCustomException("Google token is invalid or has expired");
}
要创建我的 CLIENT_ID,我按照以下链接中的说明操作:
https://developers.google.com/identity/sign-in/web/devconsole-project
问题是 verifier.verify 不断返回 null.
我检查过:
我的用户确实在谷歌注册并且数据库字段已正确填写
每次尝试 google_sign_in 时,我都会从 google 获得不同的字符串标记
my CLIENT_ID 在 Google 控制台中有效且活跃。
更让人困惑的是,这一切在一个月前还运行良好。我请病假离开,当我回来时,我的老板就这个问题欢迎我。
有人知道可能发生了什么吗?
我终于明白了
因为没人知道如何帮助我,我放弃了指定的谷歌库,从头开始自己制作令牌验证。
我在这里使用了 google-token-verifier-url-tool:
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
在页面底部:
https://developers.google.com/identity/protocols/OpenIDConnect
我找到了破译 JSON 的方法。
我所做的是,我在代码中联系他们的在线工具,获取 JSONresponse 并手动验证它。 这是我的代码:
private Map<String,String> getMapFromGoogleTokenString(final String idTokenString){
BufferedReader in = null;
try {
// get information from token by contacting the google_token_verify_tool url :
in = new BufferedReader(new InputStreamReader(
((HttpURLConnection) (new URL("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + idTokenString.trim()))
.openConnection()).getInputStream(), Charset.forName("UTF-8")));
// read information into a string buffer :
StringBuffer b = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null){
b.append(inputLine + "\n");
}
// transforming json string into Map<String,String> :
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(b.toString(), objectMapper.getTypeFactory().constructMapType(Map.class, String.class, String.class));
// exception handling :
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch(Exception e){
System.out.println("\n\n\tFailed to transform json to string\n");
e.printStackTrace();
} finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
// chack the "email_verified" and "email" values in token payload
private boolean verifyEmail(final Map<String,String> tokenPayload){
if(tokenPayload.get("email_verified")!=null && tokenPayload.get("email")!=null){
try{
return Boolean.valueOf(tokenPayload.get("email_verified")) && tokenPayload.get("email").contains("@gmail.");
}catch(Exception e){
System.out.println("\n\n\tCheck emailVerified failed - cannot parse "+tokenPayload.get("email_verified")+" to boolean\n");
}
}else{
System.out.println("\n\n\tCheck emailVerified failed - required information missing in the token");
}
return false;
}
// check token expiration is after now :
private boolean checkExpirationTime(final Map<String,String> tokenPayload){
try{
if(tokenPayload.get("exp")!=null){
// the "exp" value is in seconds and Date().getTime is in mili seconds
return Long.parseLong(tokenPayload.get("exp")+"000") > new java.util.Date().getTime();
}else{
System.out.println("\n\n\tCheck expiration failed - required information missing in the token\n");
}
}catch(Exception e){
System.out.println("\n\n\tCheck expiration failed - cannot parse "+tokenPayload.get("exp")+" into long\n");
}
return false;
}
// check that at least one CLIENT_ID matches with token values
private boolean checkAudience(final Map<String,String> tokenPayload){
if(tokenPayload.get("aud")!=null && tokenPayload.get("azp")!=null){
List<String> pom = Arrays.asList("MY_CLIENT_ID_1",
"MY_CLIENT_ID_2",
"MY_CLIENT_ID_3");
if(pom.contains(tokenPayload.get("aud")) || pom.contains(tokenPayload.get("azp"))){
return true;
}else{
System.out.println("\n\n\tCheck audience failed - audiences differ\n");
return false;
}
}
System.out.println("\n\n\tCheck audience failed - required information missing in the token\n");
return false;
}
// verify google token payload :
private boolean doTokenVerification(final Map<String,String> tokenPayload){
if(tokenPayload!=null){
return verifyEmail(tokenPayload) // check that email address is verifies
&& checkExpirationTime(tokenPayload) // check that token is not expired
&& checkAudience(tokenPayload) // check audience
;
}
return false;
}
经过这个详细的验证后,我就能准确地看到错误在哪里。前端向我发送了一个无效的 CLIENT_ID 值。 [抱怨,抱怨] 我已经问过他们大约一百次了,他们告诉我这些价值观是匹配的。 呸!
所以错误不在我原来的令牌验证代码中的某个地方,而是我办公室的通信错误。
为了安全起见,这次我将使用正确的 CLIENT_ID 恢复到原始代码。不过,我必须对 Google 图书馆提出一个抱怨——它从来没有告诉我令牌验证失败的原因。我花了几天的心血才终于弄明白。我知道他们这样做是出于安全考虑,但缺乏支持仍然令人痛心。
有类似的问题。这太愚蠢了,但我的服务器上的时间不对。我认为验证总是失败,因为令牌的到期时间在我的服务器时间宇宙中结束。
对于那些仍然有这个问题的人:
尝试 python 示例(https://developers.google.com/identity/sign-in/web/backend-auth#python)以确保您使用的是正确的 CLIENT_ID,如果不是,您将看到异常消息正确的 CLIENT_ID
使用版本
com.google.api-client
的1.31.3
和版本com.google.oauth-client
的
1.31.4
使用
com.google.api.client.json.gson.GsonFactory
作为JsonFactory
我通过发送
idToken
而不是来自客户的authToken
解决了我的问题
不确定是否还有人在看这个,但是来自 google GitHub 的代码实际上为我解决了这个问题。 https://github.com/googlearchive/gplus-verifytoken-java/tree/master/src/com/google/plus/samples/verifytoken
他们提到该项目不再积极维护,但作为这项工作的档案保留在那里。
我发现了两个原因。
刷新授权令牌的解决方案:
我们在成功登录后在响应对象上获得一个 reloadAuthResponse 方法。此外,我们获得 expires_in 属性,它为我们提供令牌将过期的毫秒数。以下是使用它的代码片段。
const handleSuccessfulGoogleResponse = (response) => {
console.log(response)
const loginDetails = {
name: response.profileObj.name,
email: response.profileObj.email,
tokenId: response.tokenId
}
//Do what is needed with the data
refreshTokenGenerator(response);
}
const refreshTokenGenerator = res => {
let refreshTime = (res.tokenObj.expires_in || 3600 - 50 * 60) * 1000;
const refreshToken = async () => {
console.log('running at ',new Date(Date.now()).toLocaleTimeString());
const refreshedResponse = await res.reloadAuthResponse();
refreshTime = (refreshedResponse.expires_in || 3600 - 50 * 60) *
1000;
const newTokenId = refreshedResponse.id_token;
//store the newTokenId and use it for the network calls
setTimeout(refreshToken, refreshTime);
}
setTimeout(refreshToken, refreshTime);
}
在这里,handleSuccessfulGoogleResponse() 在成功登录后执行。我们在其中调用 refreshTokenGenerator(),它使用 expires_in 属性(如果存在,则默认为 3600 毫秒)。然后我们使用 setTimeout() 来执行函数以在当前令牌到期之前生成新令牌。