前端回调地址:
后端回调地址:和前端一样即可
前端JS调用谷歌登录代码:
前端js
* // 构建 Google 授权 URL
* const authParams = new URLSearchParams({
* response_type: 'code', //固定
* client_id: 'YOUR_CLIENT_ID', // 请将 YOUR_CLIENT_ID 替换为实际的客户端 ID
* scope: 'openid email profile', //固定
* redirect_uri: 'YOUR_REDIRECT_URI', // 在Google配置的回调url
* });
*
* const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${authParams}`;
后端Java调用谷歌登录代码
@GetMapping("/googleLoginUrl")
public AjaxResult googleLoginUrl(HttpServletResponse response){
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
List<String> SCOPES =
Arrays.asList("https://www.googleapis.com/auth/userinfo.email");
// 设置 OAuth 2.0 授权码流对象
AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, "CLIENT_ID", "CLIENT_SECRET, SCOPES", SCOPES)
.setAccessType("offline")
.setApprovalPrompt("force") // 可选,强制用户重新授权
.build();
// 生成用户授权的 URL
AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl()
.setRedirectUri("http://localhost:8075/code");
return AjaxResult.success(authorizationUrl.build());
}
后端重定向接口随意写,写前端域名也可以
@GetMapping("/code")
public String getCode(HttpServletRequest request) {
System.out.println("调用code接口");
return request.getParameter("code");
}
后端获取code码进行验证
/**
* 使用code进行验证
* @param googleDTO
* @return
* @throws GeneralSecurityException
* @throws IOException
*/
@PostMapping("/googleLogin")
public AjaxResult googleLogin(@RequestBody GoogleDTO googleDTO) throws GeneralSecurityException, IOException {
try {
// 创建 Google 授权码流对象
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
CLIENT_ID,
CLIENT_SECRET,
Arrays.asList("openid", "email", "profile"))
.setAccessType("offline")
.build();
// 交换授权码为访问令牌
TokenResponse tokenResponse = flow.newTokenRequest(googleDTO.getCode())
.setRedirectUri("http://localhost:8075/code")
.execute();
String accessToken = tokenResponse.getAccessToken();
String userInfo = getUserInfo(accessToken);
JSONObject jsonObject = JSONObject.parseObject(userInfo);
String email = jsonObject.getString("email") ;
String userId = jsonObject.getString("id") ;
String pictureUrl = jsonObject.getString("picture") ;
//国家
String locale = jsonObject.getString("locale") ;
String name = jsonObject.getString("name") ;
//校验账号是否存在
GlobalUser checkGlobalUser = globalUserService.checkSubject(userId);
if (Objects.nonNull(checkGlobalUser)){
GlobalUser globalUser = new GlobalUser();
globalUser.setPictureUrl(pictureUrl);
globalUser.setEmail(email);
globalUser.setgoogleId(userId);
globalUser.setStatus(0);
globalUser.setId(checkGlobalUser.getId());
globalUserService.updateGlobalUser(globalUser);
}else{
GlobalUser globalUser = new GlobalUser();
globalUser.setEmail(email);
globalUser.setgoogleId(userId);
globalUser.setStatus(0);
globalUser.setPictureUrl(pictureUrl);
globalUserService.insertGlobalUser(globalUser);
}
Map<String, String> map = new HashMap<>();
map.put("email", email);
map.put("name", name);
map.put("status","0");
// 生成令牌
String token = JWTUtils.getToken(map);
AjaxResult ajax = AjaxResult.success();
ajax.put(Constants.TOKEN, token);
ajax.put(Constants.USERNAME, email);
return ajax;
}catch (Exception e){
e.printStackTrace();
return AjaxResult.error();
}
}
获取用户信息
//获取用户信息
public String getUserInfo(String accessToken) {
String url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
try {
return HttpClient4Util.getResponse4GetAsString(url,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
添加依赖maven
<dependency> <groupId>com.google.auth</groupId> <artifactId>google-auth-library-oauth2-http</artifactId> <version>0.22.2</version> </dependency> <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.32.1</version> </dependency>