google登入验证

This commit is contained in:
lu7213 committed 2026-10-14 21:01:36 -04:00
1 parent f69926dee6
commit d014cd15f0
10 files changed
+569 -1

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
# Google OpenID Connect 部署说明
## 登录与绑定策略
- Google 身份只使用 OpenID Connect 的 `sub` 作为唯一标识,不以邮箱匹配本地用户。
- 未绑定的 Google 账号不能登录,也不会自动注册本地账号。
- 用户必须先通过账号密码登录,在“个人中心 -> 账号安全”中主动绑定 Google。
- 一个本地账号只能绑定一个 Google 身份,一个 Google 身份也只能绑定一个本地账号。
## 数据库升级
部署应用前执行:
```sql
SOURCE /path/to/myEpusdt/sql/google_oauth.sql;
```
脚本只新增 `sys_user_google_oauth` 表,不修改 `sys_user` 和现有登录数据。执行前仍应按生产规范备份数据库。
## Google Cloud 配置
1. 在 Google Auth Platform 创建 Web application 类型的 OAuth Client。
2. OAuth 同意屏幕只申请 `openid`、`email`、`profile`。
3. 将后端固定回调地址登记为 Authorized redirect URI,例如:
```text
https://api.example.com/auth/google/callback
```
登记值必须与 `GOOGLE_OAUTH_REDIRECT_URI` 完全一致。生产环境必须使用 HTTPS;仅本地开发允许 `http://localhost` 或 `http://127.0.0.1`。
## 环境变量
Linux 可在应用启动前设置:
```bash
export GOOGLE_OAUTH_ENABLED=true
export GOOGLE_OAUTH_CLIENT_ID='your-client-id.apps.googleusercontent.com'
export GOOGLE_OAUTH_CLIENT_SECRET='your-client-secret'
export GOOGLE_OAUTH_REDIRECT_URI='https://api.example.com/auth/google/callback'
export GOOGLE_OAUTH_FRONTEND_RESULT_URL='https://app.example.com/auth/google/result'
```
`GOOGLE_OAUTH_CLIENT_SECRET` 只能保存于服务器环境变量或密钥管理系统,不得写入前端、日志或版本库。修改环境变量后重启后端服务。
## 发布验证
1. 使用本地账号密码登录,进入个人中心绑定 Google。
2. 退出系统,再从登录页使用已绑定的 Google 账号登录。
3. 使用未绑定的 Google 账号登录,确认页面提示先登录本地账号绑定。
4. 禁用一个已绑定的本地用户,确认 Google 登录被拒绝。
5. 确认重复回调、重复交换登录票据均被拒绝。
6. 确认原有账号密码登录、角色、菜单权限和退出登录不受影响。
## 回滚
设置 `GOOGLE_OAUTH_ENABLED=false` 并重启后端即可关闭登录入口。原有密码登录保持可用;关联表建议保留,避免重新发布后丢失既有绑定关系。
@@ -0,0 +1,83 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.GoogleOauthService;
import com.ruoyi.system.domain.SysUserGoogleOauth;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
import java.util.HashMap;
import java.util.Map;
/** Google OpenID Connect登录与当前本地账号绑定接口。 */
@RestController
@RequestMapping("/auth/google")
public class GoogleOauthController {
private final GoogleOauthService googleOauthService;
public GoogleOauthController(GoogleOauthService googleOauthService) {
this.googleOauthService = googleOauthService;
}
/** 匿名登录授权入口,只返回Google官方授权地址。 */
@GetMapping("/login-url")
public AjaxResult loginUrl() {
AjaxResult result = AjaxResult.success();
result.put("enabled", googleOauthService.isEnabled());
if (googleOauthService.isEnabled()) {
result.put("authorizationUrl", googleOauthService.buildAuthorizationUrl("LOGIN", null));
}
return result;
}
/** 已登录用户发起绑定,绑定目标用户ID从当前JWT读取。 */
@GetMapping("/bind-url")
public AjaxResult bindUrl() {
return AjaxResult.success(googleOauthService.buildAuthorizationUrl("BIND", SecurityUtils.getUserId()));
}
/** Google控制台登记的固定回调地址。 */
@GetMapping("/callback")
public RedirectView callback(@RequestParam(value = "code", required = false) String code,
@RequestParam(value = "state", required = false) String state,
@RequestParam(value = "error", required = false) String error) {
return new RedirectView(googleOauthService.handleCallback(code, state, error));
}
/** 前端使用60秒一次性票据换取原有RuoYi系统JWT。 */
@PostMapping("/exchange")
public AjaxResult exchange(@RequestBody Map<String, String> request) {
AjaxResult result = AjaxResult.success();
result.put(Constants.TOKEN, googleOauthService.exchangeTicket(request.get("ticket")));
return result;
}
@GetMapping("/binding")
public AjaxResult binding() {
SysUserGoogleOauth binding = googleOauthService.getBinding(SecurityUtils.getUserId());
Map<String, Object> view = new HashMap<>();
view.put("enabled", googleOauthService.isEnabled());
view.put("bound", binding != null);
if (binding != null) {
view.put("email", binding.getEmail());
view.put("displayName", binding.getDisplayName());
view.put("avatarUrl", binding.getAvatarUrl());
view.put("createdAt", binding.getCreatedAt());
}
return AjaxResult.success(view);
}
@DeleteMapping("/binding")
public AjaxResult unbind() {
googleOauthService.unbind(SecurityUtils.getUserId());
return AjaxResult.success("Google账号已解绑");
}
}
@@ -208,3 +208,12 @@ luqj:
callback: http://39.98.190.128:8080/aliyun/oss/callback # 文件上传成功后的回调地址 callback: http://39.98.190.128:8080/aliyun/oss/callback # 文件上传成功后的回调地址
dir: dir:
prefix: lu7213/images/ # 上传文件夹路径前缀 prefix: lu7213/images/ # 上传文件夹路径前缀
# Google OpenID Connect登录。Client Secret只能通过环境变量或外部配置提供。
google:
oauth:
enabled: ${GOOGLE_OAUTH_ENABLED:false}
client-id: ${GOOGLE_OAUTH_CLIENT_ID:}
client-secret: ${GOOGLE_OAUTH_CLIENT_SECRET:}
redirect-uri: ${GOOGLE_OAUTH_REDIRECT_URI:}
frontend-result-url: ${GOOGLE_OAUTH_FRONTEND_RESULT_URL:}
+8 -1
View File
@@ -91,6 +91,13 @@
<version>2.2.13.RELEASE</version> <version>2.2.13.RELEASE</version>
</dependency> </dependency>
<!-- Google OpenID Connect ID Token签名和声明校验,兼容JDK 8。 -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.34.1</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -118,6 +118,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.authorizeRequests() .authorizeRequests()
// 对于登录login 验证码captchaImage 允许匿名访问 // 对于登录login 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/simple-login", "/captchaImage").anonymous() .antMatchers("/login", "/simple-login", "/captchaImage").anonymous()
.antMatchers("/auth/google/login-url", "/auth/google/callback", "/auth/google/exchange").permitAll()
.antMatchers( .antMatchers(
// HttpMethod.GET, // HttpMethod.GET,
antPatterns.toArray(new String[0]) antPatterns.toArray(new String[0])
@@ -0,0 +1,316 @@
package com.ruoyi.framework.web.service;
import com.alibaba.fastjson.JSONObject;
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.gson.GsonFactory;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.SysUserGoogleOauth;
import com.ruoyi.system.mapper.SysUserGoogleOauthMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/** Google OpenID Connect登录与本地账号绑定服务。 */
@Service
public class GoogleOauthService {
private static final Logger LOGGER = LoggerFactory.getLogger(GoogleOauthService.class);
private static final String PROVIDER = "google";
private static final String STATE_PREFIX = "oauth:google:state:";
private static final String STATE_USED_PREFIX = "oauth:google:state-used:";
private static final String TICKET_PREFIX = "oauth:google:ticket:";
private static final String TICKET_USED_PREFIX = "oauth:google:ticket-used:";
private static final int STATE_TTL_MINUTES = 10;
private static final int TICKET_TTL_SECONDS = 60;
private final RedisCache redisCache;
private final SysUserGoogleOauthMapper identityMapper;
private final ISysUserService userService;
private final UserDetailsServiceImpl userDetailsService;
private final TokenService tokenService;
private final RestTemplate restTemplate;
@Value("${google.oauth.enabled:false}") private boolean enabled;
@Value("${google.oauth.client-id:}") private String clientId;
@Value("${google.oauth.client-secret:}") private String clientSecret;
@Value("${google.oauth.redirect-uri:}") private String redirectUri;
@Value("${google.oauth.frontend-result-url:}") private String frontendResultUrl;
public GoogleOauthService(RedisCache redisCache, SysUserGoogleOauthMapper identityMapper,
ISysUserService userService, UserDetailsServiceImpl userDetailsService, TokenService tokenService) {
this.redisCache = redisCache;
this.identityMapper = identityMapper;
this.userService = userService;
this.userDetailsService = userDetailsService;
this.tokenService = tokenService;
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(60000);
requestFactory.setReadTimeout(60000);
this.restTemplate = new RestTemplate(requestFactory);
}
/** 创建登录或绑定授权地址,绑定时的用户ID只保存在服务端Redis上下文。 */
public String buildAuthorizationUrl(String purpose, Long userId) {
checkConfigured();
if (!("LOGIN".equals(purpose) || "BIND".equals(purpose))) {
throw new CustomException("不支持的Google授权用途");
}
if ("BIND".equals(purpose) && userId == null) {
throw new CustomException("请先登录本地账号再绑定Google");
}
String state = IdUtils.fastUUID();
String nonce = IdUtils.fastUUID();
JSONObject context = new JSONObject();
context.put("purpose", purpose);
context.put("userId", userId);
context.put("nonce", nonce);
redisCache.setCacheObject(STATE_PREFIX + state,
context.toJSONString(), STATE_TTL_MINUTES, TimeUnit.MINUTES);
return UriComponentsBuilder.fromHttpUrl("https://accounts.google.com/o/oauth2/v2/auth")
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectUri)
.queryParam("response_type", "code")
.queryParam("scope", "openid email profile")
.queryParam("state", state)
.queryParam("nonce", nonce)
.queryParam("prompt", "select_account")
.build().encode().toUriString();
}
/** 处理Google回调。返回前端结果URL,URL中只包含短期一次性票据或非敏感错误码。 */
@Transactional(rollbackFor = Exception.class)
public String handleCallback(String code, String state, String oauthError) {
if (StringUtils.isNotBlank(oauthError)) {
return resultUrl("cancelled", null);
}
if (StringUtils.isBlank(code) || StringUtils.isBlank(state)) {
return resultUrl("invalid_callback", null);
}
String contextJson = redisCache.getCacheObject(STATE_PREFIX + state);
if (StringUtils.isBlank(contextJson)
|| !claim(STATE_USED_PREFIX + state, STATE_TTL_MINUTES, TimeUnit.MINUTES)) {
return resultUrl("invalid_state", null);
}
redisCache.deleteObject(STATE_PREFIX + state);
try {
JSONObject context = JSONObject.parseObject(contextJson);
GoogleProfile profile = exchangeAndVerify(code, context.getString("nonce"));
if ("BIND".equals(context.getString("purpose"))) {
Long userId = context.getLong("userId");
bind(userId, profile);
LOGGER.info("Google账号绑定成功,本地用户ID:{}", userId);
return resultUrl("bound", null);
}
SysUserGoogleOauth identity = identityMapper.selectByProviderUserId(PROVIDER, profile.getSubject());
if (identity == null) {
return resultUrl("not_bound", null);
}
updateProviderProfile(identity, profile);
SysUser user = requireActiveUser(identity.getUserId());
String ticket = IdUtils.fastUUID();
redisCache.setCacheObject(TICKET_PREFIX + ticket, user.getUserId(),
TICKET_TTL_SECONDS, TimeUnit.SECONDS);
return resultUrl("success", ticket);
} catch (CustomException exception) {
return resultUrl(exception.getMessage(), null);
} catch (DuplicateKeyException exception) {
LOGGER.warn("Google账号绑定发生并发唯一键冲突");
return resultUrl("already_bound_elsewhere", null);
} catch (Exception exception) {
LOGGER.warn("Google OAuth回调处理失败:{}", exception.getClass().getSimpleName());
return resultUrl("oauth_failed", null);
}
}
/** 一次性票据换取现有RuoYi JWT;重复交换会被Redis原子锁拒绝。 */
public String exchangeTicket(String ticket) {
if (StringUtils.isBlank(ticket)
|| !claim(TICKET_USED_PREFIX + ticket, TICKET_TTL_SECONDS, TimeUnit.SECONDS)) {
throw new CustomException("Google登录票据无效或已使用");
}
Long userId = redisCache.getCacheObject(TICKET_PREFIX + ticket);
redisCache.deleteObject(TICKET_PREFIX + ticket);
if (userId == null) {
throw new CustomException("Google登录票据已过期");
}
SysUser user = requireActiveUser(userId);
LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(user.getUserName());
return tokenService.createToken(loginUser);
}
public SysUserGoogleOauth getBinding(Long userId) {
return identityMapper.selectByUserId(PROVIDER, userId);
}
public void unbind(Long userId) {
if (identityMapper.deleteByUserId(PROVIDER, userId) > 0) {
LOGGER.info("Google账号解绑成功,本地用户ID:{}", userId);
}
}
private GoogleProfile exchangeAndVerify(String code, String expectedNonce)
throws IOException, GeneralSecurityException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add("code", code);
form.add("client_id", clientId);
form.add("client_secret", clientSecret);
form.add("redirect_uri", redirectUri);
form.add("grant_type", "authorization_code");
ResponseEntity<String> response = restTemplate.postForEntity(
"https://oauth2.googleapis.com/token", new HttpEntity<>(form, headers), String.class);
JSONObject tokenResponse = JSONObject.parseObject(response.getBody());
String idTokenValue = tokenResponse == null ? null : tokenResponse.getString("id_token");
if (StringUtils.isBlank(idTokenValue)) {
throw new CustomException("oauth_failed");
}
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(
new NetHttpTransport(), GsonFactory.getDefaultInstance())
.setAudience(Collections.singletonList(clientId)).build();
GoogleIdToken idToken = verifier.verify(idTokenValue);
if (idToken == null) {
throw new CustomException("invalid_token");
}
GoogleIdToken.Payload payload = idToken.getPayload();
if (!expectedNonce.equals(String.valueOf(payload.get("nonce")))) {
throw new CustomException("invalid_nonce");
}
if (!Boolean.TRUE.equals(payload.getEmailVerified())) {
throw new CustomException("email_not_verified");
}
return new GoogleProfile(payload.getSubject(), payload.getEmail(),
stringClaim(payload, "name"), stringClaim(payload, "picture"));
}
private void bind(Long userId, GoogleProfile profile) {
requireActiveUser(userId);
SysUserGoogleOauth byGoogle = identityMapper.selectByProviderUserId(PROVIDER, profile.getSubject());
if (byGoogle != null && !userId.equals(byGoogle.getUserId())) {
throw new CustomException("already_bound_elsewhere");
}
SysUserGoogleOauth byUser = identityMapper.selectByUserId(PROVIDER, userId);
if (byUser != null && !profile.getSubject().equals(byUser.getProviderUserId())) {
throw new CustomException("local_already_bound");
}
if (byUser != null) {
updateProviderProfile(byUser, profile);
return;
}
Date now = new Date();
SysUserGoogleOauth identity = new SysUserGoogleOauth();
identity.setUserId(userId);
identity.setProvider(PROVIDER);
identity.setProviderUserId(profile.getSubject());
identity.setEmail(profile.getEmail());
identity.setDisplayName(profile.getDisplayName());
identity.setAvatarUrl(profile.getAvatarUrl());
identity.setCreatedAt(now);
identity.setUpdatedAt(now);
identityMapper.insert(identity);
}
private void updateProviderProfile(SysUserGoogleOauth identity, GoogleProfile profile) {
identity.setEmail(profile.getEmail());
identity.setDisplayName(profile.getDisplayName());
identity.setAvatarUrl(profile.getAvatarUrl());
identity.setUpdatedAt(new Date());
identityMapper.updateProfile(identity);
}
private SysUser requireActiveUser(Long userId) {
SysUser user = userService.selectUserById(userId);
if (user == null || UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
throw new CustomException("local_account_unavailable");
}
if (!UserStatus.OK.getCode().equals(user.getStatus())) {
throw new CustomException("local_account_disabled");
}
return user;
}
private boolean claim(String key, int ttl, TimeUnit unit) {
Boolean success = redisCache.redisTemplate.opsForValue().setIfAbsent(key, "1", ttl, unit);
return Boolean.TRUE.equals(success);
}
private String resultUrl(String status, String ticket) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(frontendResultUrl)
.queryParam("status", status);
if (StringUtils.isNotBlank(ticket)) {
builder.queryParam("ticket", ticket);
}
return builder.build().encode().toUriString();
}
private void checkConfigured() {
if (!enabled) {
throw new CustomException("Google登录未启用");
}
if (StringUtils.isBlank(clientId) || StringUtils.isBlank(clientSecret)
|| StringUtils.isBlank(redirectUri) || StringUtils.isBlank(frontendResultUrl)) {
throw new CustomException("Google登录配置不完整");
}
URI redirect = URI.create(redirectUri);
URI frontendResult = URI.create(frontendResultUrl);
if (!isSecureUrl(redirect)) {
throw new CustomException("Google生产回调地址必须使用HTTPS");
}
if (!isSecureUrl(frontendResult)) {
throw new CustomException("Google生产前端结果地址必须使用HTTPS");
}
}
private boolean isSecureUrl(URI uri) {
return "https".equalsIgnoreCase(uri.getScheme())
|| ("http".equalsIgnoreCase(uri.getScheme())
&& ("localhost".equalsIgnoreCase(uri.getHost())
|| "127.0.0.1".equals(uri.getHost())));
}
private String stringClaim(GoogleIdToken.Payload payload, String name) {
Object value = payload.get(name);
return value == null ? null : String.valueOf(value);
}
public boolean isEnabled() { return enabled; }
private static class GoogleProfile {
private final String subject;
private final String email;
private final String displayName;
private final String avatarUrl;
GoogleProfile(String subject, String email, String displayName, String avatarUrl) { this.subject = subject; this.email = email; this.displayName = displayName; this.avatarUrl = avatarUrl; }
public String getSubject() { return subject; }
public String getEmail() { return email; }
public String getDisplayName() { return displayName; }
public String getAvatarUrl() { return avatarUrl; }
}
}
@@ -0,0 +1,38 @@
package com.ruoyi.system.domain;
import java.io.Serializable;
import java.util.Date;
/** 本地用户与Google OpenID Connect身份的关联记录。 */
public class SysUserGoogleOauth implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Long userId;
private String provider;
private String providerUserId;
private String email;
private String displayName;
private String avatarUrl;
private Date createdAt;
private Date updatedAt;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public String getProvider() { return provider; }
public void setProvider(String provider) { this.provider = provider; }
public String getProviderUserId() { return providerUserId; }
public void setProviderUserId(String providerUserId) { this.providerUserId = providerUserId; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getDisplayName() { return displayName; }
public void setDisplayName(String displayName) { this.displayName = displayName; }
public String getAvatarUrl() { return avatarUrl; }
public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; }
public Date getCreatedAt() { return createdAt; }
public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; }
public Date getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; }
}
@@ -0,0 +1,14 @@
package com.ruoyi.system.mapper;
import com.ruoyi.system.domain.SysUserGoogleOauth;
import org.apache.ibatis.annotations.Param;
public interface SysUserGoogleOauthMapper {
SysUserGoogleOauth selectByProviderUserId(@Param("provider") String provider,
@Param("providerUserId") String providerUserId);
SysUserGoogleOauth selectByUserId(@Param("provider") String provider,
@Param("userId") Long userId);
int insert(SysUserGoogleOauth identity);
int updateProfile(SysUserGoogleOauth identity);
int deleteByUserId(@Param("provider") String provider, @Param("userId") Long userId);
}
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.SysUserGoogleOauthMapper">
<resultMap id="GoogleIdentityResult" type="com.ruoyi.system.domain.SysUserGoogleOauth">
<id property="id" column="id"/><result property="userId" column="user_id"/>
<result property="provider" column="provider"/><result property="providerUserId" column="provider_user_id"/>
<result property="email" column="email"/><result property="displayName" column="display_name"/>
<result property="avatarUrl" column="avatar_url"/><result property="createdAt" column="created_at"/>
<result property="updatedAt" column="updated_at"/>
</resultMap>
<select id="selectByProviderUserId" resultMap="GoogleIdentityResult">
SELECT * FROM sys_user_google_oauth WHERE provider=#{provider} AND provider_user_id=#{providerUserId}
</select>
<select id="selectByUserId" resultMap="GoogleIdentityResult">
SELECT * FROM sys_user_google_oauth WHERE provider=#{provider} AND user_id=#{userId}
</select>
<insert id="insert" parameterType="com.ruoyi.system.domain.SysUserGoogleOauth" useGeneratedKeys="true" keyProperty="id">
INSERT INTO sys_user_google_oauth(user_id,provider,provider_user_id,email,display_name,avatar_url,created_at,updated_at)
VALUES(#{userId},#{provider},#{providerUserId},#{email},#{displayName},#{avatarUrl},#{createdAt},#{updatedAt})
</insert>
<update id="updateProfile">
UPDATE sys_user_google_oauth SET email=#{email},display_name=#{displayName},avatar_url=#{avatarUrl},updated_at=#{updatedAt}
WHERE provider=#{provider} AND provider_user_id=#{providerUserId}
</update>
<delete id="deleteByUserId">DELETE FROM sys_user_google_oauth WHERE provider=#{provider} AND user_id=#{userId}</delete>
</mapper>
+17
View File
@@ -0,0 +1,17 @@
-- Google OpenID Connect身份关联表。
-- 未绑定的Google身份不得登录;绑定操作必须由已登录的本地账号发起。
CREATE TABLE IF NOT EXISTS sys_user_google_oauth (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
user_id BIGINT NOT NULL COMMENT '本地用户ID,对应sys_user.user_id',
provider VARCHAR(32) NOT NULL DEFAULT 'google' COMMENT '身份提供商,当前固定为google',
provider_user_id VARCHAR(128) NOT NULL COMMENT 'Google稳定用户标识sub,不使用邮箱作为身份主键',
email VARCHAR(255) DEFAULT NULL COMMENT 'Google返回的已验证邮箱,仅用于展示',
display_name VARCHAR(255) DEFAULT NULL COMMENT 'Google账号显示名称',
avatar_url VARCHAR(1024) DEFAULT NULL COMMENT 'Google账号头像地址',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次绑定时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后资料同步时间',
PRIMARY KEY (id),
UNIQUE KEY uk_google_provider_user (provider, provider_user_id) COMMENT '同一Google身份只能绑定一个本地用户',
UNIQUE KEY uk_google_provider_local_user (provider, user_id) COMMENT '一个本地用户只能绑定一个Google身份',
KEY idx_google_user_id (user_id) COMMENT '按本地用户查询绑定信息'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='本地用户与Google登录身份关联表';