首先創(chuàng)建OAuth 2.0 客戶端 ID
配置url,必須是https的,同時復制好客戶端id 和密鑰
配置回調(diào)url文章來源:http://www.zghlxwxcb.cn/news/detail-631809.html
/**
* Google授權(quán)登錄跳轉(zhuǎn)。但是會重定向,建議前端跳轉(zhuǎn)
*
* 前端js
* // 構(gòu)建 Google 授權(quán) 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配置的回調(diào)url
* });
*
* const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?${authParams}`;
*
通過Java接口跳轉(zhuǎn)Google登錄頁面,會重定向,建議前端跳轉(zhuǎn)
* @param response
* @return
* @throws IOException
*/
@GetMapping("/google-login")
@NoAuth
public CommonResult<String> googleLogin(HttpServletResponse response) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
// 設(shè)置 OAuth 2.0 授權(quán)碼流對象
AuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, SCOPES)
.setAccessType("offline")
.setApprovalPrompt("force") // 可選,強制用戶重新授權(quán)
.build();
// 生成用戶授權(quán)的 URL
AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl()
.setRedirectUri(REDIRECT_URI);
// 重定向用戶到授權(quán) URL
response.sendRedirect(authorizationUrl.build());
return new CommonResult("success");
}
回調(diào)接口文章來源地址http://www.zghlxwxcb.cn/news/detail-631809.html
@GetMapping("/google-callback")
@NoAuth //不需要登錄
public ResponseEntity<String> googleCallback(@RequestParam("code") String authorizationCode) throws IOException {
System.out.println("google-callback code = "+authorizationCode);
// 創(chuàng)建 Google 授權(quán)碼流對象
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
CLIENT_ID,
CLIENT_SECRET,
Arrays.asList("openid", "email", "profile"))
.setAccessType("offline")
.build();
// 交換授權(quán)碼為訪問令牌
TokenResponse tokenResponse = flow.newTokenRequest(authorizationCode)
.setRedirectUri(REDIRECT_URI)
.execute();
String accessToken = tokenResponse.getAccessToken();
// System.out.println("google accessToken: "+accessToken);
String userInfo = getUserInfo(accessToken);
// System.out.println("userInfo: "+userInfo);
/** 格式
* {
* "iss": "https://accounts.google.com",
* "sub": "123456789012345678901", 表示用戶的唯一標識符,通常是用戶的Google ID。
* "aud": "your-client-id",
* "email": "user@example.com",
* "email_verified": true,
* "exp": 1627889766,
* "iat": 1627886166
* }
*/
JSONObject jsonObject = JSONObject.parseObject(userInfo);
String email = jsonObject.getString("email") ;
//登錄邏輯
JSONObject userJson = loginByEmail(email);
String redirectUrl = "https://funflixvideo.com/#/?userId="+userJson.getString("userId")+"&sessionId="+userJson.getString("sessionId");
// 重定向到 H5 頁面,并帶上 session ID
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(redirectUrl));
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
//獲取用戶信息
public String getUserInfo(String accessToken) {
String url = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
try {
return HttpClient4Utils.httpGet(url, null, "utf-8", 30);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
到了這里,關(guān)于Java實現(xiàn)Google授權(quán)登錄,OAuth 2.0登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!