Google OAuth 2.0
是其中一种常见的第三方登录方式,广泛应用于各类网站和应用程序。通过 Google OAuth 2.0
,用户可以使用其 Google 账户轻松登录第三方网站,而不必创建额外的账户。本文将介绍如何集成 Google OAuth 2.0
服务,实现用户在第三方网站上的登录。Google API Console
获取 OAuth 2.0 凭据。点击左侧边栏的“Credentials”选项,然后创建一个客户端 ID(OAuth client ID)。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google Login</title>
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<h2>Google 登录示例</h2>
<button id="googleSignInButton">使用 Google 登录</button>
<script>
document.getElementById('googleSignInButton').onclick = function () {
// Google OAuth 2.0 URL
const clientId = '994578547547-gc6XXXX0vp9hl.apps.googleusercontent.com'; // 替换为你的Google客户端ID
const redirectUri = 'http://localhost:8000/api/google/login'; // 替换为后端的回调登录URI
const scope = 'email profile';
const responseType = 'code';
const googleAuthUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=${responseType}&scope=${scope}`;
// 重定向到 Google OAuth 2.0 授权页面
window.location.href = googleAuthUrl;
};
</script>
</body>
</html>
google:
token-apply-url: https://oauth2.googleapis.com/token
userinfo-url: https://www.googleapis.com/oauth2/v3/userinfo
oauth2:
client-id: 994578547547-gc6uXXXXjtpk0vp9hl.apps.googleusercontent.com
client-secret: GOCSPX-nWFVXXXXFImvw3iHLNkR
@Api(tags = "谷歌服务相关请求")
@RestController
@RequestMapping("/api/google")
@RequiredArgsConstructor
public class GoogleController {
@Value("${google.oauth2.client-id}")
private String clientId;
@Value("${google.oauth2.client-secret}")
private String clientSecret;
@Value("${google.token-apply-url}")
private String tokenEndpoint;
@Value("${google.userinfo-url}")
private String userInfoEndpoint;
private final RestTemplate restTemplate;
private final TokenProvider tokenProvider;
private final UserDetailsService userDetailsService;
private final UserService userService;
private final SecurityProperties properties;
private final OnlineUserService onlineUserService;
@AnonymousGetMapping("/login")
public ResponseEntity<Object> handleGoogleLogin(@RequestParam("code") String authorizationCode, HttpServletRequest req) {
// Step 1: 用授权码获取 Access Token
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("client_id", clientId);
params.add("client_secret", clientSecret);
params.add("code", authorizationCode);
params.add("redirect_uri", "http://localhost:8000/api/google/login");
params.add("grant_type", "authorization_code");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(tokenEndpoint, request, Map.class);
String accessToken = (String) response.getBody().get("access_token");
// Step 2: 用 Access Token 获取用户信息
HttpHeaders userInfoHeaders = new HttpHeaders();
userInfoHeaders.setBearerAuth(accessToken);
HttpEntity<String> userInfoRequest = new HttpEntity<>(userInfoHeaders);
ResponseEntity<Map> userInfoResponse = restTemplate.exchange(userInfoEndpoint, HttpMethod.GET, userInfoRequest, Map.class);
Map<String, Object> userInfo = userInfoResponse.getBody();
String googleId = (String) userInfo.get("sub");
String email = (String) userInfo.get("email");
String name = (String) userInfo.get("name");
String picture = (String) userInfo.get("picture");
// 用户登录逻辑、并返回用户信息、会话信息
}
}
Google OAuth 2.0
服务,第三方网站可以实现简单、快捷且安全的用户登录方式。OAuth 2.0 的流程保障了用户的隐私安全,不需要将敏感信息(如密码)提供给第三方应用。同时,使用 Google 登录可以减少用户的注册步骤,提升用户体验。👋 你好,我是 Lorin 洛林,一位 Java 后端技术开发者!座右铭:Technology has the power to make the world a better place.
🚀 我对技术的热情是我不断学习和分享的动力。我的博客是一个关于Java生态系统、后端开发和最新技术趋势的地方。
🧠 作为一个 Java 后端技术爱好者,我不仅热衷于探索语言的新特性和技术的深度,还热衷于分享我的见解和最佳实践。我相信知识的分享和社区合作可以帮助我们共同成长。
💡 在我的博客上,你将找到关于Java核心概念、JVM 底层技术、常用框架如Spring和Mybatis 、MySQL等数据库管理、RabbitMQ、Rocketmq等消息中间件、性能优化等内容的深入文章。我也将分享一些编程技巧和解决问题的方法,以帮助你更好地掌握Java编程。
🌐 我鼓励互动和建立社区,因此请留下你的问题、建议或主题请求,让我知道你感兴趣的内容。此外,我将分享最新的互联网和技术资讯,以确保你与技术世界的最新发展保持联系。我期待与你一起在技术之路上前进,一起探讨技术世界的无限可能性。
📖 保持关注我的博客,让我们共同追求技术卓越。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。