google登入验证
This commit is contained in:
1 parent
f69926dee6
commit
d014cd15f0
10 files changed
+569
-1
No files matched your search
@@ -118,6 +118,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
.authorizeRequests()
|
||||
// 对于登录login 验证码captchaImage 允许匿名访问
|
||||
.antMatchers("/login", "/simple-login", "/captchaImage").anonymous()
|
||||
.antMatchers("/auth/google/login-url", "/auth/google/callback", "/auth/google/exchange").permitAll()
|
||||
.antMatchers(
|
||||
// HttpMethod.GET,
|
||||
antPatterns.toArray(new String[0])
|
||||
|
||||
+316
@@ -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; }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user