功能迭代
This commit is contained in:
1 parent
5fc7d4564c
commit
84184a2dd1
41 files changed
+1054
-8
No files matched your search
@@ -46,7 +46,7 @@ public class AdminSecurityConfig {
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http, ObjectMapper mapper) throws Exception {
|
||||
return http.csrf(csrf -> csrf.disable())
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/admin/v1/auth/login", "/uploads/**").permitAll()
|
||||
.requestMatchers("/api/admin/v1/auth/login", "/api/admin/v1/gsc/oauth/callback", "/uploads/**").permitAll()
|
||||
.requestMatchers("/api/admin/**").authenticated().anyRequest().permitAll())
|
||||
.exceptionHandling(errors -> errors.authenticationEntryPoint((request, response, exception) -> {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.shoplix.admin.controller;
|
||||
|
||||
import com.shoplix.admin.modules.common.res.CommonAdminRes;
|
||||
import com.shoplix.admin.modules.gsc.req.*;
|
||||
import com.shoplix.admin.modules.gsc.res.*;
|
||||
import com.shoplix.admin.service.AdminGscService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
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.RestController;
|
||||
import org.springframework.web.servlet.view.RedirectView;
|
||||
|
||||
/** 运营后台Google Search Console接口。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/v1/gsc")
|
||||
public class AdminGscController {
|
||||
private final AdminGscService service;
|
||||
|
||||
/** 注入Google Search Console业务。 */
|
||||
public AdminGscController(AdminGscService service) { this.service = service; }
|
||||
|
||||
/** 查询当前站点GSC连接状态。 */
|
||||
@PostMapping("/connection")
|
||||
public GscConnectionAdminRes connection(@Valid @RequestBody GscSiteAdminReq request) {
|
||||
return service.connection(request.siteCode());
|
||||
}
|
||||
|
||||
/** 创建Google OAuth授权地址。 */
|
||||
@PostMapping("/authorization")
|
||||
public GscAuthorizationAdminRes authorization(@Valid @RequestBody GscAuthorizationAdminReq request) {
|
||||
return service.authorization(request);
|
||||
}
|
||||
|
||||
/** 接收Google OAuth授权回调。 */
|
||||
@GetMapping("/oauth/callback")
|
||||
public RedirectView callback(@Valid @ModelAttribute GscOauthCallbackAdminReq request) {
|
||||
return new RedirectView(service.callback(request));
|
||||
}
|
||||
|
||||
/** 解除当前站点GSC授权。 */
|
||||
@PostMapping("/disconnect")
|
||||
public CommonAdminRes disconnect(@Valid @RequestBody GscSiteAdminReq request) {
|
||||
service.disconnect(request.siteCode());
|
||||
return CommonAdminRes.success();
|
||||
}
|
||||
|
||||
/** 查询关键词、页面与收录效果。 */
|
||||
@PostMapping("/statistics")
|
||||
public GscStatisticsAdminRes statistics(@Valid @RequestBody GscStatisticsAdminReq request) {
|
||||
return service.statistics(request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.shoplix.admin.modules.gsc.req;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/** 创建GSC授权地址请求。 */
|
||||
public record GscAuthorizationAdminReq(
|
||||
/** 站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode,
|
||||
/** 授权结束后的管理后台绝对地址。 */ @NotBlank @Size(max = 500)
|
||||
@Pattern(regexp = "^https?://.+") String returnUrl) {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.shoplix.admin.modules.gsc.req;
|
||||
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/** Google OAuth回调查询参数。 */
|
||||
public record GscOauthCallbackAdminReq(
|
||||
/** Google授权码。 */ @Size(max = 1000) String code,
|
||||
/** OAuth防重放状态码。 */ @Size(max = 64) String state,
|
||||
/** Google返回的授权错误。 */ @Size(max = 200) String error) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.shoplix.admin.modules.gsc.req;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
/** GSC站点级请求。 */
|
||||
public record GscSiteAdminReq(
|
||||
/** 站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.shoplix.admin.modules.gsc.req;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** 查询GSC统计数据请求。 */
|
||||
public record GscStatisticsAdminReq(
|
||||
/** 站点业务编号。 */ @NotBlank @Size(max = 16) String siteCode,
|
||||
/** 统计开始日期。 */ @NotNull LocalDate startDate,
|
||||
/** 统计结束日期。 */ @NotNull LocalDate endDate) {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
/** GSC授权地址响应。 */
|
||||
public record GscAuthorizationAdminRes(
|
||||
/** Google OAuth授权地址。 */ String authorizationUrl) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
import com.shoplix.modules.gsc.enums.GscConnectionOperationEnum;
|
||||
import java.util.List;
|
||||
|
||||
/** GSC授权连接状态响应。 */
|
||||
public record GscConnectionAdminRes(
|
||||
/** Google OAuth是否已配置。 */ boolean oauthConfigured,
|
||||
/** 当前站点是否已连接。 */ boolean connected,
|
||||
/** 授权Google账户邮箱。 */ String accountEmail,
|
||||
/** 已匹配的Search Console站点资源。 */ String propertyUri,
|
||||
/** 连接状态枚举值。 */ String status,
|
||||
/** 连接状态文案。 */ String statusLabel,
|
||||
/** 当前连接状态允许操作。 */ List<GscConnectionOperationEnum> operations,
|
||||
/** 最后更新时间毫秒时间戳。 */ Long updateTime) {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
/** GSC关键词效果行。 */
|
||||
public record GscKeywordAdminRes(
|
||||
/** 搜索关键词。 */ String keyword,
|
||||
/** 点击次数。 */ double clicks,
|
||||
/** 曝光次数。 */ double impressions,
|
||||
/** 点击率,取值0至1。 */ double ctr,
|
||||
/** 平均搜索排名。 */ double position) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
/** GSC核心效果指标。 */
|
||||
public record GscMetricAdminRes(
|
||||
/** 总点击次数。 */ double clicks,
|
||||
/** 总曝光次数。 */ double impressions,
|
||||
/** 平均点击率,取值0至1。 */ double ctr,
|
||||
/** 平均搜索排名。 */ double position) {
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
/** GSC页面效果行。 */
|
||||
public record GscPageAdminRes(
|
||||
/** 收录页面地址。 */ String page,
|
||||
/** 点击次数。 */ double clicks,
|
||||
/** 曝光次数。 */ double impressions,
|
||||
/** 点击率,取值0至1。 */ double ctr,
|
||||
/** 平均搜索排名。 */ double position) {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** GSC站点收录及搜索效果统计响应。 */
|
||||
public record GscStatisticsAdminRes(
|
||||
/** 站点地图已提交URL数量。 */ long submittedUrls,
|
||||
/** 站点地图已索引URL数量。 */ long indexedUrls,
|
||||
/** 产生曝光的关键词数量。 */ int keywordCount,
|
||||
/** 核心搜索效果指标。 */ GscMetricAdminRes metric,
|
||||
/** 每日效果趋势。 */ List<GscTrendAdminRes> trends,
|
||||
/** 关键词效果明细。 */ List<GscKeywordAdminRes> keywords,
|
||||
/** 页面效果明细。 */ List<GscPageAdminRes> pages) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.shoplix.admin.modules.gsc.res;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** GSC每日效果趋势。 */
|
||||
public record GscTrendAdminRes(
|
||||
/** 统计日期。 */ LocalDate date,
|
||||
/** 点击次数。 */ double clicks,
|
||||
/** 曝光次数。 */ double impressions,
|
||||
/** 点击率,取值0至1。 */ double ctr,
|
||||
/** 平均搜索排名。 */ double position) {
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package com.shoplix.admin.service;
|
||||
|
||||
import com.shoplix.admin.modules.gsc.req.GscAuthorizationAdminReq;
|
||||
import com.shoplix.admin.modules.gsc.req.GscOauthCallbackAdminReq;
|
||||
import com.shoplix.admin.modules.gsc.req.GscStatisticsAdminReq;
|
||||
import com.shoplix.admin.modules.gsc.res.*;
|
||||
import com.shoplix.admin.third.gsc.*;
|
||||
import com.shoplix.common.code.enums.BusinessCodePrefixEnum;
|
||||
import com.shoplix.common.exception.BusinessException;
|
||||
import com.shoplix.common.utils.BusinessCodeUtils;
|
||||
import com.shoplix.modules.gsc.repository.entity.GscConnectionEntity;
|
||||
import com.shoplix.modules.gsc.enums.GscConnectionStatusEnum;
|
||||
import com.shoplix.modules.gsc.enums.GscOauthStateStatusEnum;
|
||||
import com.shoplix.modules.gsc.repository.entity.GscOauthStateEntity;
|
||||
import com.shoplix.modules.gsc.repository.service.GscConnectionRepositoryService;
|
||||
import com.shoplix.modules.gsc.repository.service.GscOauthStateRepositoryService;
|
||||
import com.shoplix.modules.site.repository.service.SiteDomainRepositoryService;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/** Google Search Console授权与统计业务。 */
|
||||
@Service
|
||||
public class AdminGscService {
|
||||
private final GscConnectionRepositoryService connectionRepository;
|
||||
private final GscOauthStateRepositoryService stateRepository;
|
||||
private final SiteDomainRepositoryService domainRepository;
|
||||
private final GscClient client;
|
||||
private final GscProperties properties;
|
||||
private final GscTokenCipher tokenCipher;
|
||||
private final BusinessCodeUtils codeUtils;
|
||||
private final MessageSource messageSource;
|
||||
|
||||
/** 注入GSC业务依赖。 */
|
||||
public AdminGscService(GscConnectionRepositoryService connectionRepository,
|
||||
GscOauthStateRepositoryService stateRepository,
|
||||
SiteDomainRepositoryService domainRepository, GscClient client,
|
||||
GscProperties properties, GscTokenCipher tokenCipher,
|
||||
BusinessCodeUtils codeUtils, MessageSource messageSource) {
|
||||
this.connectionRepository = connectionRepository;
|
||||
this.stateRepository = stateRepository;
|
||||
this.domainRepository = domainRepository;
|
||||
this.client = client;
|
||||
this.properties = properties;
|
||||
this.tokenCipher = tokenCipher;
|
||||
this.codeUtils = codeUtils;
|
||||
this.messageSource = messageSource;
|
||||
}
|
||||
|
||||
/** 查询当前站点GSC连接状态。 */
|
||||
public GscConnectionAdminRes connection(String siteCode) {
|
||||
return connectionRepository.findBySiteCode(siteCode)
|
||||
.map(item -> {
|
||||
GscConnectionStatusEnum status = GscConnectionStatusEnum.valueOf(item.getStatus());
|
||||
return new GscConnectionAdminRes(properties.configured(), status == GscConnectionStatusEnum.CONNECTED,
|
||||
item.getAccountEmail(), item.getPropertyUri(), status.name(), status.getLabel(), status.getOperations(), item.getUpdateTime());
|
||||
})
|
||||
.orElseGet(() -> new GscConnectionAdminRes(properties.configured(), false, null, null,
|
||||
GscConnectionStatusEnum.DISCONNECTED.name(), GscConnectionStatusEnum.DISCONNECTED.getLabel(),
|
||||
GscConnectionStatusEnum.DISCONNECTED.getOperations(), null));
|
||||
}
|
||||
|
||||
/** 创建一次性Google OAuth授权地址。 */
|
||||
@Transactional
|
||||
public GscAuthorizationAdminRes authorization(GscAuthorizationAdminReq request) {
|
||||
requireConfigured();
|
||||
validateReturnUrl(request.returnUrl());
|
||||
domainRepository.findPrimaryBySiteCode(request.siteCode())
|
||||
.orElseThrow(() -> exception("GSC_DOMAIN_REQUIRED", "gsc.domain.required"));
|
||||
String stateCode = randomState();
|
||||
long now = System.currentTimeMillis();
|
||||
GscOauthStateEntity state = new GscOauthStateEntity();
|
||||
state.setStateCode(stateCode);
|
||||
state.setSiteCode(request.siteCode());
|
||||
state.setRedirectUri(request.returnUrl());
|
||||
state.setExpireTime(now + 10 * 60 * 1000L);
|
||||
state.setUsed(GscOauthStateStatusEnum.UNUSED.getValue());
|
||||
state.setCreateTime(now);
|
||||
if (stateRepository.insert(state) != 1) throw exception("GSC_STATE_SAVE_FAILED", "gsc.state.save.failed");
|
||||
return new GscAuthorizationAdminRes(client.authorizationUrl(stateCode));
|
||||
}
|
||||
|
||||
/** 处理Google OAuth回调并返回管理后台跳转地址。 */
|
||||
@Transactional
|
||||
public String callback(GscOauthCallbackAdminReq request) {
|
||||
if (request.state() == null || request.state().isBlank()) return "/?gscAuth=failed";
|
||||
GscOauthStateEntity state = stateRepository.findUsable(request.state(), System.currentTimeMillis()).orElse(null);
|
||||
if (state == null || stateRepository.markUsed(request.state()) != 1) return "/?gscAuth=expired";
|
||||
if (request.error() != null || request.code() == null || request.code().isBlank()) {
|
||||
return appendResult(state.getRedirectUri(), "denied");
|
||||
}
|
||||
try {
|
||||
GscTokenResponse token = client.exchangeCode(request.code());
|
||||
if (token.refreshToken() == null || token.refreshToken().isBlank()) {
|
||||
throw exception("GSC_REFRESH_TOKEN_REQUIRED", "gsc.refresh-token.required");
|
||||
}
|
||||
String domain = domainRepository.findPrimaryBySiteCode(state.getSiteCode())
|
||||
.orElseThrow(() -> exception("GSC_DOMAIN_REQUIRED", "gsc.domain.required")).getDomain();
|
||||
String propertyUri = matchProperty(domain, client.properties(token.accessToken()));
|
||||
saveConnection(state.getSiteCode(), propertyUri, client.accountEmail(token.accessToken()), token.refreshToken());
|
||||
return appendResult(state.getRedirectUri(), "success");
|
||||
} catch (BusinessException exception) {
|
||||
return appendResult(state.getRedirectUri(), "failed");
|
||||
}
|
||||
}
|
||||
|
||||
/** 解除当前站点Google Search Console授权。 */
|
||||
@Transactional
|
||||
public void disconnect(String siteCode) {
|
||||
GscConnectionEntity entity = connected(siteCode);
|
||||
client.revoke(tokenCipher.decrypt(entity.getRefreshTokenCiphertext()));
|
||||
entity.setStatus(GscConnectionStatusEnum.DISCONNECTED.name());
|
||||
entity.setRefreshTokenCiphertext("");
|
||||
entity.setUpdateTime(System.currentTimeMillis());
|
||||
if (connectionRepository.update(entity) != 1) throw exception("GSC_DISCONNECT_FAILED", "gsc.disconnect.failed");
|
||||
}
|
||||
|
||||
/** 查询当前站点关键词、页面与收录效果。 */
|
||||
public GscStatisticsAdminRes statistics(GscStatisticsAdminReq request) {
|
||||
validateDateRange(request.startDate(), request.endDate());
|
||||
GscConnectionEntity connection = connected(request.siteCode());
|
||||
String accessToken = client.refreshAccessToken(tokenCipher.decrypt(connection.getRefreshTokenCiphertext()));
|
||||
var metricRows = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of(), 1);
|
||||
var metric = metricRows.isEmpty() ? new GscMetricAdminRes(0, 0, 0, 0) : toMetric(metricRows.getFirst());
|
||||
var trends = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of("date"), 500)
|
||||
.stream().map(row -> new GscTrendAdminRes(LocalDate.parse(row.keys().getFirst()), row.clicks(), row.impressions(), row.ctr(), row.position()))
|
||||
.sorted(Comparator.comparing(GscTrendAdminRes::date)).toList();
|
||||
var keywords = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of("query"), 1000)
|
||||
.stream().map(row -> new GscKeywordAdminRes(row.keys().getFirst(), row.clicks(), row.impressions(), row.ctr(), row.position())).toList();
|
||||
var pages = client.analytics(accessToken, connection.getPropertyUri(), request.startDate(), request.endDate(), List.of("page"), 500)
|
||||
.stream().map(row -> new GscPageAdminRes(row.keys().getFirst(), row.clicks(), row.impressions(), row.ctr(), row.position())).toList();
|
||||
long[] coverage = client.sitemapCoverage(accessToken, connection.getPropertyUri());
|
||||
return new GscStatisticsAdminRes(coverage[0], coverage[1], keywords.size(), metric, trends, keywords, pages);
|
||||
}
|
||||
|
||||
/** 保存或覆盖站点GSC连接。 */
|
||||
private void saveConnection(String siteCode, String propertyUri, String email, String refreshToken) {
|
||||
long now = System.currentTimeMillis();
|
||||
GscConnectionEntity entity = connectionRepository.findBySiteCode(siteCode).orElseGet(() -> {
|
||||
GscConnectionEntity created = new GscConnectionEntity();
|
||||
created.setConnectionCode(codeUtils.generate(BusinessCodePrefixEnum.GSC_CONNECTION));
|
||||
created.setSiteCode(siteCode);
|
||||
created.setCreateTime(now);
|
||||
return created;
|
||||
});
|
||||
entity.setPropertyUri(propertyUri);
|
||||
entity.setAccountEmail(email);
|
||||
entity.setRefreshTokenCiphertext(tokenCipher.encrypt(refreshToken));
|
||||
entity.setStatus(GscConnectionStatusEnum.CONNECTED.name());
|
||||
entity.setUpdateTime(now);
|
||||
int affected = entity.getId() == null ? connectionRepository.insert(entity) : connectionRepository.update(entity);
|
||||
if (affected != 1) throw exception("GSC_CONNECTION_SAVE_FAILED", "gsc.connection.save.failed");
|
||||
}
|
||||
|
||||
/** 匹配店铺域名对应的GSC资源。 */
|
||||
private String matchProperty(String domain, List<GscProperty> properties) {
|
||||
String normalized = domain.toLowerCase(Locale.ROOT).replaceFirst("^www\\.", "");
|
||||
return properties.stream().map(GscProperty::siteUrl)
|
||||
.filter(value -> propertyDomain(value).equals(normalized)).findFirst()
|
||||
.orElseThrow(() -> exception("GSC_PROPERTY_NOT_FOUND", "gsc.property.not-found"));
|
||||
}
|
||||
|
||||
/** 从域名属性或URL前缀属性提取主机名。 */
|
||||
private String propertyDomain(String propertyUri) {
|
||||
try {
|
||||
if (propertyUri.startsWith("sc-domain:")) return propertyUri.substring(10).replaceFirst("^www\\.", "").toLowerCase(Locale.ROOT);
|
||||
return URI.create(propertyUri).getHost().replaceFirst("^www\\.", "").toLowerCase(Locale.ROOT);
|
||||
} catch (Exception exception) { return ""; }
|
||||
}
|
||||
|
||||
/** 查询有效连接。 */
|
||||
private GscConnectionEntity connected(String siteCode) {
|
||||
return connectionRepository.findBySiteCode(siteCode).filter(item -> GscConnectionStatusEnum.CONNECTED.name().equals(item.getStatus()))
|
||||
.orElseThrow(() -> exception("GSC_NOT_CONNECTED", "gsc.not-connected"));
|
||||
}
|
||||
|
||||
/** 校验统计日期范围。 */
|
||||
private void validateDateRange(LocalDate startDate, LocalDate endDate) {
|
||||
if (endDate.isBefore(startDate) || ChronoUnit.DAYS.between(startDate, endDate) > 365) {
|
||||
throw exception("GSC_DATE_RANGE_INVALID", "gsc.date-range.invalid");
|
||||
}
|
||||
}
|
||||
|
||||
/** 转换核心效果指标。 */
|
||||
private GscMetricAdminRes toMetric(GscAnalyticsRow row) {
|
||||
return new GscMetricAdminRes(row.clicks(), row.impressions(), row.ctr(), row.position());
|
||||
}
|
||||
|
||||
/** 确认Google OAuth客户端已配置。 */
|
||||
private void requireConfigured() {
|
||||
if (!properties.configured()) throw exception("GSC_OAUTH_NOT_CONFIGURED", "gsc.oauth.not-configured");
|
||||
}
|
||||
|
||||
/** 限制OAuth完成后的回跳地址必须与后台回调使用同一主机。 */
|
||||
private void validateReturnUrl(String returnUrl) {
|
||||
try {
|
||||
String returnHost = URI.create(returnUrl).getHost();
|
||||
String callbackHost = URI.create(properties.getCallbackUrl()).getHost();
|
||||
if (returnHost == null || !returnHost.equalsIgnoreCase(callbackHost)) {
|
||||
throw exception("GSC_RETURN_URL_INVALID", "gsc.return-url.invalid");
|
||||
}
|
||||
} catch (BusinessException exception) { throw exception; }
|
||||
catch (Exception exception) { throw exception("GSC_RETURN_URL_INVALID", "gsc.return-url.invalid"); }
|
||||
}
|
||||
|
||||
/** 生成不可预测的一次性OAuth状态码。 */
|
||||
private String randomState() {
|
||||
byte[] bytes = new byte[32];
|
||||
new SecureRandom().nextBytes(bytes);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
/** 为回跳地址追加授权结果。 */
|
||||
private String appendResult(String url, String result) {
|
||||
return url + (url.contains("?") ? "&" : "?") + "gscAuth=" + URLEncoder.encode(result, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** 创建多语言业务异常。 */
|
||||
private BusinessException exception(String code, String messageKey) {
|
||||
return new BusinessException(code, messageSource.getMessage(messageKey, null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Google Search Analytics单行统计。 */
|
||||
public record GscAnalyticsRow(List<String> keys, double clicks, double impressions, double ctr, double position) {
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.shoplix.common.exception.BusinessException;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
|
||||
/** Google OAuth与Search Console外部接口客户端。 */
|
||||
@Component
|
||||
public class GscClient {
|
||||
private static final String SCOPE = "https://www.googleapis.com/auth/webmasters.readonly https://www.googleapis.com/auth/userinfo.email";
|
||||
private final GscProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final MessageSource messageSource;
|
||||
private final HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build();
|
||||
|
||||
/** 注入GSC配置与JSON解析器。 */
|
||||
public GscClient(GscProperties properties, ObjectMapper objectMapper, MessageSource messageSource) {
|
||||
this.properties = properties;
|
||||
this.objectMapper = objectMapper;
|
||||
this.messageSource = messageSource;
|
||||
}
|
||||
|
||||
/** 生成Google OAuth授权地址。 */
|
||||
public String authorizationUrl(String state) {
|
||||
return "https://accounts.google.com/o/oauth2/v2/auth?client_id=" + encode(properties.getClientId())
|
||||
+ "&redirect_uri=" + encode(properties.getCallbackUrl()) + "&response_type=code&scope=" + encode(SCOPE)
|
||||
+ "&access_type=offline&prompt=consent&include_granted_scopes=true&state=" + encode(state);
|
||||
}
|
||||
|
||||
/** 使用授权码交换访问及刷新令牌。 */
|
||||
public GscTokenResponse exchangeCode(String code) {
|
||||
String body = form(Map.of("code", code, "client_id", properties.getClientId(),
|
||||
"client_secret", properties.getClientSecret(), "redirect_uri", properties.getCallbackUrl(),
|
||||
"grant_type", "authorization_code"));
|
||||
JsonNode json = send(HttpRequest.newBuilder(URI.create("https://oauth2.googleapis.com/token"))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.ofString(body)).build());
|
||||
return new GscTokenResponse(json.path("access_token").asText(), json.path("refresh_token").asText(), json.path("expires_in").asLong());
|
||||
}
|
||||
|
||||
/** 使用刷新令牌取得短期访问令牌。 */
|
||||
public String refreshAccessToken(String refreshToken) {
|
||||
String body = form(Map.of("refresh_token", refreshToken, "client_id", properties.getClientId(),
|
||||
"client_secret", properties.getClientSecret(), "grant_type", "refresh_token"));
|
||||
return send(HttpRequest.newBuilder(URI.create("https://oauth2.googleapis.com/token"))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.ofString(body)).build())
|
||||
.path("access_token").asText();
|
||||
}
|
||||
|
||||
/** 查询授权Google账户邮箱。 */
|
||||
public String accountEmail(String accessToken) {
|
||||
return get("https://www.googleapis.com/oauth2/v2/userinfo", accessToken).path("email").asText();
|
||||
}
|
||||
|
||||
/** 查询账户可访问的Search Console站点资源。 */
|
||||
public List<GscProperty> properties(String accessToken) {
|
||||
List<GscProperty> result = new ArrayList<>();
|
||||
for (JsonNode item : get("https://www.googleapis.com/webmasters/v3/sites", accessToken).path("siteEntry")) {
|
||||
result.add(new GscProperty(item.path("siteUrl").asText(), item.path("permissionLevel").asText()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 查询Search Analytics统计行。 */
|
||||
public List<GscAnalyticsRow> analytics(String accessToken, String propertyUri, LocalDate startDate,
|
||||
LocalDate endDate, List<String> dimensions, int rowLimit) {
|
||||
try {
|
||||
String body = objectMapper.writeValueAsString(Map.of("startDate", startDate.toString(), "endDate", endDate.toString(),
|
||||
"dimensions", dimensions, "rowLimit", rowLimit, "dataState", "all"));
|
||||
JsonNode json = send(HttpRequest.newBuilder(URI.create("https://www.googleapis.com/webmasters/v3/sites/"
|
||||
+ encode(propertyUri) + "/searchAnalytics/query"))
|
||||
.header("Authorization", "Bearer " + accessToken).header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body)).build());
|
||||
List<GscAnalyticsRow> result = new ArrayList<>();
|
||||
for (JsonNode row : json.path("rows")) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
row.path("keys").forEach(key -> keys.add(key.asText()));
|
||||
result.add(new GscAnalyticsRow(keys, row.path("clicks").asDouble(), row.path("impressions").asDouble(),
|
||||
row.path("ctr").asDouble(), row.path("position").asDouble()));
|
||||
}
|
||||
return result;
|
||||
} catch (BusinessException exception) { throw exception; }
|
||||
catch (Exception exception) { throw externalError(exception); }
|
||||
}
|
||||
|
||||
/** 统计站点地图已发现与已索引URL数量。 */
|
||||
public long[] sitemapCoverage(String accessToken, String propertyUri) {
|
||||
JsonNode json = get("https://www.googleapis.com/webmasters/v3/sites/" + encode(propertyUri) + "/sitemaps", accessToken);
|
||||
long submitted = 0L;
|
||||
long indexed = 0L;
|
||||
for (JsonNode sitemap : json.path("sitemap")) {
|
||||
for (JsonNode content : sitemap.path("contents")) {
|
||||
submitted += content.path("submitted").asLong();
|
||||
indexed += content.path("indexed").asLong();
|
||||
}
|
||||
}
|
||||
return new long[]{submitted, indexed};
|
||||
}
|
||||
|
||||
/** 撤销Google刷新令牌。 */
|
||||
public void revoke(String refreshToken) {
|
||||
send(HttpRequest.newBuilder(URI.create("https://oauth2.googleapis.com/revoke?token=" + encode(refreshToken)))
|
||||
.header("Content-Type", "application/x-www-form-urlencoded").POST(HttpRequest.BodyPublishers.noBody()).build());
|
||||
}
|
||||
|
||||
/** 发送Bearer GET请求。 */
|
||||
private JsonNode get(String url, String accessToken) {
|
||||
return send(HttpRequest.newBuilder(URI.create(url)).header("Authorization", "Bearer " + accessToken).GET().build());
|
||||
}
|
||||
|
||||
/** 发送外部请求并统一检查响应。 */
|
||||
private JsonNode send(HttpRequest request) {
|
||||
try {
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
throw externalError(null);
|
||||
}
|
||||
return response.body().isBlank() ? objectMapper.createObjectNode() : objectMapper.readTree(response.body());
|
||||
} catch (BusinessException exception) { throw exception; }
|
||||
catch (Exception exception) { throw externalError(exception); }
|
||||
}
|
||||
|
||||
/** 创建统一外部接口异常。 */
|
||||
private BusinessException externalError(Exception exception) {
|
||||
return new BusinessException("GSC_EXTERNAL_REQUEST_FAILED",
|
||||
messageSource.getMessage("gsc.external.request.failed", null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
|
||||
/** URL编码文本。 */ private String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); }
|
||||
/** 构建表单请求体。 */ private String form(Map<String, String> values) {
|
||||
return values.entrySet().stream().map(item -> encode(item.getKey()) + "=" + encode(item.getValue()))
|
||||
.collect(java.util.stream.Collectors.joining("&"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** Google Search Console外部接口配置。 */
|
||||
@Component
|
||||
public class GscProperties {
|
||||
/** Google OAuth客户端编号。 */ private final String clientId;
|
||||
/** Google OAuth客户端密钥。 */ private final String clientSecret;
|
||||
/** Google OAuth回调地址。 */ private final String callbackUrl;
|
||||
/** OAuth令牌本地加密密钥。 */ private final String tokenKey;
|
||||
|
||||
/** 注入Google Search Console配置。 */
|
||||
public GscProperties(@Value("${shoplix.gsc.client-id:}") String clientId,
|
||||
@Value("${shoplix.gsc.client-secret:}") String clientSecret,
|
||||
@Value("${shoplix.gsc.callback-url:http://localhost:8081/api/admin/v1/gsc/oauth/callback}") String callbackUrl,
|
||||
@Value("${shoplix.gsc.token-key:shoplix-local-gsc-token-key-change-in-production}") String tokenKey) {
|
||||
this.clientId = clientId;
|
||||
this.clientSecret = clientSecret;
|
||||
this.callbackUrl = callbackUrl;
|
||||
this.tokenKey = tokenKey;
|
||||
}
|
||||
|
||||
/** 获取OAuth客户端编号。 */ public String getClientId() { return clientId; }
|
||||
/** 获取OAuth客户端密钥。 */ public String getClientSecret() { return clientSecret; }
|
||||
/** 获取OAuth回调地址。 */ public String getCallbackUrl() { return callbackUrl; }
|
||||
/** 获取令牌加密密钥。 */ public String getTokenKey() { return tokenKey; }
|
||||
/** 判断Google OAuth是否完成配置。 */ public boolean configured() { return !clientId.isBlank() && !clientSecret.isBlank(); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
/** Google Search Console站点资源。 */
|
||||
public record GscProperty(String siteUrl, String permissionLevel) {
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
import com.shoplix.common.exception.BusinessException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 使用AES-GCM保护持久化OAuth令牌。 */
|
||||
@Component
|
||||
public class GscTokenCipher {
|
||||
private static final int IV_LENGTH = 12;
|
||||
private final SecretKeySpec key;
|
||||
private final MessageSource messageSource;
|
||||
|
||||
/** 根据配置密钥初始化令牌加密器。 */
|
||||
public GscTokenCipher(GscProperties properties, MessageSource messageSource) {
|
||||
this.messageSource = messageSource;
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(properties.getTokenKey().getBytes(StandardCharsets.UTF_8));
|
||||
this.key = new SecretKeySpec(digest, "AES");
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("Unable to initialize GSC token cipher", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/** 加密OAuth令牌。 */
|
||||
public String encrypt(String value) {
|
||||
try {
|
||||
byte[] iv = new byte[IV_LENGTH];
|
||||
new SecureRandom().nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
|
||||
byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
|
||||
byte[] output = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, output, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, output, iv.length, encrypted.length);
|
||||
return Base64.getEncoder().encodeToString(output);
|
||||
} catch (Exception exception) {
|
||||
throw exception("GSC_TOKEN_ENCRYPT_FAILED", "gsc.token.encrypt.failed");
|
||||
}
|
||||
}
|
||||
|
||||
/** 解密OAuth令牌。 */
|
||||
public String decrypt(String value) {
|
||||
try {
|
||||
byte[] input = Base64.getDecoder().decode(value);
|
||||
byte[] iv = java.util.Arrays.copyOfRange(input, 0, IV_LENGTH);
|
||||
byte[] encrypted = java.util.Arrays.copyOfRange(input, IV_LENGTH, input.length);
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
|
||||
return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
|
||||
} catch (Exception exception) {
|
||||
throw exception("GSC_TOKEN_DECRYPT_FAILED", "gsc.token.decrypt.failed");
|
||||
}
|
||||
}
|
||||
|
||||
/** 创建多语言令牌处理异常。 */
|
||||
private BusinessException exception(String code, String messageKey) {
|
||||
return new BusinessException(code, messageSource.getMessage(messageKey, null, LocaleContextHolder.getLocale()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
/** Google OAuth令牌交换结果。 */
|
||||
public record GscTokenResponse(String accessToken, String refreshToken, long expiresIn) {
|
||||
}
|
||||
@@ -45,3 +45,8 @@ shoplix:
|
||||
access-key: ${SHOPLIX_OSS_ACCESS_KEY:shoplix-test}
|
||||
secret-key: ${SHOPLIX_OSS_SECRET_KEY:shoplix-test}
|
||||
path-style-access: ${SHOPLIX_OSS_PATH_STYLE_ACCESS:true}
|
||||
gsc:
|
||||
client-id: ${SHOPLIX_GSC_CLIENT_ID:}
|
||||
client-secret: ${SHOPLIX_GSC_CLIENT_SECRET:}
|
||||
callback-url: ${SHOPLIX_GSC_CALLBACK_URL:http://localhost:8081/api/admin/v1/gsc/oauth/callback}
|
||||
token-key: ${SHOPLIX_GSC_TOKEN_KEY:shoplix-local-gsc-token-key-change-in-production}
|
||||
@@ -0,0 +1,27 @@
|
||||
CREATE TABLE gsc_connection (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '数据库内部主键',
|
||||
connection_code CHAR(16) NOT NULL COMMENT 'GSC连接业务编号',
|
||||
site_code CHAR(16) NOT NULL COMMENT '所属站点业务编号',
|
||||
property_uri VARCHAR(500) NOT NULL COMMENT 'Google Search Console站点资源地址',
|
||||
account_email VARCHAR(200) NOT NULL COMMENT '授权Google账户邮箱',
|
||||
refresh_token_ciphertext TEXT NOT NULL COMMENT '加密后的OAuth刷新令牌',
|
||||
status VARCHAR(20) NOT NULL COMMENT '连接状态:CONNECTED已连接,DISCONNECTED已解绑,EXPIRED授权失效',
|
||||
create_time BIGINT NOT NULL COMMENT '创建时间毫秒时间戳',
|
||||
update_time BIGINT NOT NULL COMMENT '更新时间毫秒时间戳',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_gsc_connection_code (connection_code),
|
||||
UNIQUE KEY uk_gsc_connection_site (site_code)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Google Search Console站点授权连接';
|
||||
|
||||
CREATE TABLE gsc_oauth_state (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '数据库内部主键',
|
||||
state_code CHAR(64) NOT NULL COMMENT 'OAuth防重放随机状态码',
|
||||
site_code CHAR(16) NOT NULL COMMENT '发起授权的站点业务编号',
|
||||
redirect_uri VARCHAR(500) NOT NULL COMMENT '授权完成后的后台跳转地址',
|
||||
expire_time BIGINT NOT NULL COMMENT '状态码失效时间毫秒时间戳',
|
||||
used TINYINT NOT NULL DEFAULT 0 COMMENT '使用状态:0未使用,1已使用',
|
||||
create_time BIGINT NOT NULL COMMENT '创建时间毫秒时间戳',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_gsc_oauth_state_code (state_code),
|
||||
KEY idx_gsc_oauth_state_expire (expire_time, used)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Google Search Console OAuth临时状态';
|
||||
@@ -20,3 +20,16 @@ crm.tag.save-failed=Failed to save customer tag
|
||||
store.domain.exists=This domain is already bound to another store
|
||||
store.domain.save-failed=Failed to save the store domain
|
||||
store.domain.invalid=Enter a valid domain, for example www.example.com
|
||||
gsc.domain.required=Configure the store domain before connecting Google Search Console
|
||||
gsc.state.save.failed=Failed to create the Google authorization state
|
||||
gsc.refresh-token.required=Google did not return a refresh token; revoke the app authorization and reconnect
|
||||
gsc.property.not-found=No Search Console property matching the store domain was found in this Google account
|
||||
gsc.connection.save.failed=Failed to save the Google Search Console connection
|
||||
gsc.disconnect.failed=Failed to disconnect Google Search Console
|
||||
gsc.not-connected=This store is not connected to Google Search Console
|
||||
gsc.date-range.invalid=The date range is invalid; each query supports up to 365 days
|
||||
gsc.oauth.not-configured=The Google OAuth client is not configured
|
||||
gsc.return-url.invalid=The Google authorization return URL is invalid
|
||||
gsc.external.request.failed=Google Search Console is temporarily unavailable; check the authorization and retry
|
||||
gsc.token.encrypt.failed=Failed to save the Google authorization token
|
||||
gsc.token.decrypt.failed=Failed to read the Google authorization token; reconnect the account
|
||||
@@ -20,3 +20,16 @@ crm.tag.save-failed=客户标签保存失败
|
||||
store.domain.exists=该域名已绑定其他店铺
|
||||
store.domain.save-failed=店铺域名保存失败
|
||||
store.domain.invalid=请输入有效域名,例如 www.example.com
|
||||
gsc.domain.required=请先在店铺信息中配置店铺域名
|
||||
gsc.state.save.failed=Google授权状态创建失败
|
||||
gsc.refresh-token.required=Google未返回刷新令牌,请撤销应用授权后重新连接
|
||||
gsc.property.not-found=当前Google账户中未找到与店铺域名匹配的Search Console资源,请先完成域名验证
|
||||
gsc.connection.save.failed=Google Search Console连接保存失败
|
||||
gsc.disconnect.failed=Google Search Console解绑失败
|
||||
gsc.not-connected=当前店铺尚未连接Google Search Console
|
||||
gsc.date-range.invalid=统计日期范围无效,单次最多查询365天
|
||||
gsc.oauth.not-configured=系统尚未配置Google OAuth客户端
|
||||
gsc.return-url.invalid=Google授权回跳地址不合法
|
||||
gsc.external.request.failed=Google Search Console接口暂时不可用,请检查授权后重试
|
||||
gsc.token.encrypt.failed=Google授权令牌保存失败
|
||||
gsc.token.decrypt.failed=Google授权令牌读取失败,请重新授权
|
||||
@@ -20,3 +20,16 @@ crm.tag.save-failed=客戶標籤儲存失敗
|
||||
store.domain.exists=該網域已綁定其他店鋪
|
||||
store.domain.save-failed=店鋪網域儲存失敗
|
||||
store.domain.invalid=請輸入有效網域,例如 www.example.com
|
||||
gsc.domain.required=請先在店鋪資訊中設定店鋪網域
|
||||
gsc.state.save.failed=Google授權狀態建立失敗
|
||||
gsc.refresh-token.required=Google未傳回刷新權杖,請撤銷應用程式授權後重新連線
|
||||
gsc.property.not-found=目前Google帳戶中找不到與店鋪網域相符的Search Console資源,請先完成網域驗證
|
||||
gsc.connection.save.failed=Google Search Console連線儲存失敗
|
||||
gsc.disconnect.failed=Google Search Console解除連線失敗
|
||||
gsc.not-connected=目前店鋪尚未連線Google Search Console
|
||||
gsc.date-range.invalid=統計日期範圍無效,單次最多查詢365天
|
||||
gsc.oauth.not-configured=系統尚未設定Google OAuth客戶端
|
||||
gsc.return-url.invalid=Google授權回跳地址不合法
|
||||
gsc.external.request.failed=Google Search Console介面暫時無法使用,請檢查授權後重試
|
||||
gsc.token.encrypt.failed=Google授權權杖儲存失敗
|
||||
gsc.token.decrypt.failed=Google授權權杖讀取失敗,請重新授權
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.shoplix.admin.third.gsc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.support.StaticMessageSource;
|
||||
|
||||
/** GSC OAuth令牌加密器测试。 */
|
||||
class GscTokenCipherTest {
|
||||
/** 验证令牌加密后不可读且能够完整解密。 */
|
||||
@Test
|
||||
void shouldEncryptAndDecryptToken() {
|
||||
GscProperties properties = new GscProperties("client", "secret", "http://localhost/callback", "unit-test-token-key");
|
||||
GscTokenCipher cipher = new GscTokenCipher(properties, new StaticMessageSource());
|
||||
String encrypted = cipher.encrypt("refresh-token-value");
|
||||
assertNotEquals("refresh-token-value", encrypted);
|
||||
assertEquals("refresh-token-value", cipher.decrypt(encrypted));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user