feat(oidc): 统一认证身份关联接口改为仅本人可操作

- 移除身份关联接口的权限标识校验
- 增加当前用户校验,拒绝操作他人的身份关联
- 扩展脚本清理管理员代绑权限项
This commit is contained in:
Ray.Hao committed 2026-10-28 08:25:41 +08:00
1 parent 49b27b26b5
commit e77d0b1f4f
191 files changed
+5898 -3271

No files matched your search

@@ -0,0 +1,22 @@
package com.youlai.boot.auth.oidc.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
/**
* 统一认证启用条件
*
* @author Ray.Hao
* @since 4.12.0
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnBooleanProperty(prefix = "security.oidc", name = "enabled")
public @interface ConditionalOnOidcEnabled {
}
@@ -0,0 +1,48 @@
package com.youlai.boot.auth.oidc.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.ClientRegistrations;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
/**
* 启用 OIDC 时注册客户端并读取发现文档
*
* @author Ray.Hao
* @since 4.12.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcClientRegistrationConfig {
// OAuth 入口与回调的注册标识;不作为持久化账号归属
public static final String REGISTRATION_ID = "youlai";
private final OidcProperties oidcProperties;
/**
* 根据 issuer 发现端点,使用授权码登录
*/
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
ClientRegistration registration = ClientRegistrations
.fromIssuerLocation(oidcProperties.getIssuer())
.registrationId(REGISTRATION_ID)
.clientName("统一认证")
.clientId(oidcProperties.getClientId())
.clientSecret(oidcProperties.getClientSecret())
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope(OidcScopes.OPENID, OidcScopes.PROFILE)
.build();
return new InMemoryClientRegistrationRepository(registration);
}
}
@@ -0,0 +1,43 @@
package com.youlai.boot.auth.oidc.config;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
/**
* OIDC 登录配置
*
* @author Ray.Hao
* @since 4.12.0
*/
@Data
@Component
@ConditionalOnOidcEnabled
@Validated
@ConfigurationProperties(prefix = "security.oidc")
public class OidcProperties {
private boolean enabled = false;
// 身份表中的稳定标识;更换认证中心时使用新值或迁移关联
@NotBlank
@Pattern(regexp = "[a-z][a-z0-9-]{0,63}")
private String provider = "oidc-main";
// 必须与认证中心公布的 issuer 完全一致
@NotBlank
private String issuer;
@NotBlank
private String clientId;
@NotBlank
private String clientSecret;
// 认证成功后的前端回调地址
@NotBlank
private String frontendCallbackUri;
}
@@ -0,0 +1,67 @@
package com.youlai.boot.auth.oidc.config;
import com.youlai.boot.auth.oidc.handler.OidcLoginHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestCustomizers;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
/**
* OIDC 授权与票据兑换的安全配置
*
* @author Ray.Hao
* @since 4.12.0
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcSecurityConfig {
private final OidcLoginHandler oidcLoginHandler;
private final ClientRegistrationRepository clientRegistrationRepository;
/**
* 临时授权会话只用于 OIDC 流程,不参与业务接口认证
*/
@Bean
@Order(0)
public SecurityFilterChain oidcSecurityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatcher("/oauth2/authorization/**", "/login/oauth2/code/**",
"/api/v1/auth/oidc/tickets/exchange")
.authorizeHttpRequests(authorize -> authorize.anyRequest().permitAll())
.oauth2Login(login -> login
.successHandler(oidcLoginHandler)
.failureHandler(oidcLoginHandler)
.authorizationEndpoint(endpoint -> endpoint
.authorizationRequestResolver(createAuthorizationRequestResolver())))
// 票据兑换校验一次性票据和浏览器 Cookie
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/v1/auth/oidc/tickets/exchange"))
.requestCache(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.cors(withDefaults());
return http.build();
}
/**
* 授权码流程附加 PKCE(S256),授权请求的 code_verifier 保存在临时会话中
*/
private OAuth2AuthorizationRequestResolver createAuthorizationRequestResolver() {
DefaultOAuth2AuthorizationRequestResolver resolver =
new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository);
resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
return resolver;
}
}
@@ -0,0 +1,44 @@
package com.youlai.boot.auth.oidc.controller;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.model.form.OidcTicketExchangeForm;
import com.youlai.boot.auth.oidc.service.OidcLoginService;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.web.ratelimit.RateLimit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
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;
/**
* OIDC 登录票据兑换接口
*
* @author Ray.Hao
* @since 4.12.0
*/
@Tag(name = "01.认证中心")
@RestController
@RequestMapping("/api/v1/auth/oidc")
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcAuthController {
private final OidcLoginService oidcLoginService;
/**
* 消费一次性认证票据并创建本地会话
*/
@Operation(summary = "[OIDC] 票据兑换登录令牌")
@PostMapping("/tickets/exchange")
@RateLimit
public Result<TokenPair> exchangeTicket(@RequestBody @Valid OidcTicketExchangeForm form,
HttpServletRequest request) {
return Result.success(oidcLoginService.exchangeTicket(form.getTicket(), request));
}
}
@@ -0,0 +1,107 @@
package com.youlai.boot.auth.oidc.controller;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.config.OidcProperties;
import com.youlai.boot.auth.oidc.model.form.OidcUserIdentityForm;
import com.youlai.boot.auth.oidc.model.vo.OidcUserIdentityVO;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.ActionTypeEnum;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.session.SessionService;
import com.youlai.boot.framework.security.util.SecurityUtils;
import com.youlai.boot.system.model.entity.UserIdentity;
import com.youlai.boot.system.service.UserIdentityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Objects;
/**
* 当前用户与认证中心的身份关联
*
* @author Ray.Hao
* @since 4.13.0
*/
@Tag(name = "02.用户接口")
@Validated
@RestController
@ConditionalOnOidcEnabled
@RequestMapping("/api/v1/users/{userId}/oidc-identity")
@RequiredArgsConstructor
public class OidcUserIdentityController {
private final OidcProperties oidcProperties;
private final UserIdentityService userIdentityService;
private final SessionService sessionService;
/**
* 查询当前用户在当前认证源下的身份关联
*/
@Operation(summary = "查看统一认证身份")
@GetMapping
public Result<OidcUserIdentityVO> getIdentity(
@Parameter(description = "本地用户 ID") @PathVariable @Positive Long userId
) {
requireSelf(userId);
UserIdentity identity = userIdentityService.getIdentity(userId, oidcProperties.getProvider());
return Result.success(new OidcUserIdentityVO(
oidcProperties.getIssuer(), identity == null ? null : identity.getProviderAccountId()));
}
/**
* 保存当前用户的身份关联,拒绝占用其他用户的身份
*/
@Operation(summary = "设置统一认证身份")
@PutMapping
@Log(module = LogModuleEnum.USER, value = ActionTypeEnum.UPDATE)
public Result<Void> setIdentity(
@Parameter(description = "本地用户 ID") @PathVariable @Positive Long userId,
@RequestBody @Valid OidcUserIdentityForm form
) {
requireSelf(userId);
if (userIdentityService.setIdentity(userId, oidcProperties.getProvider(), form.getSubject())) {
// 关联改变后撤销该用户的现有会话;相同 subject 重复保存不触发下线
sessionService.revokeUserSessions(userId);
}
return Result.success();
}
/**
* 解除当前用户在当前认证源下的身份关联
*/
@Operation(summary = "解除统一认证身份")
@DeleteMapping
@Log(module = LogModuleEnum.USER, value = ActionTypeEnum.DELETE)
public Result<Void> removeIdentity(
@Parameter(description = "本地用户 ID") @PathVariable @Positive Long userId
) {
requireSelf(userId);
if (userIdentityService.removeIdentity(userId, oidcProperties.getProvider())) {
sessionService.revokeUserSessions(userId);
}
return Result.success();
}
/**
* 只允许操作当前登录用户自己的身份关联
*/
private void requireSelf(Long userId) {
if (!Objects.equals(userId, SecurityUtils.getUserId())) {
throw new BusinessException("只能操作自己的统一认证身份");
}
}
}
@@ -0,0 +1,110 @@
package com.youlai.boot.auth.oidc.handler;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.config.OidcProperties;
import com.youlai.boot.auth.oidc.service.OidcTicketService;
import com.youlai.boot.framework.security.session.LoginContext;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.system.service.UserIdentityService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 处理 OIDC 登录结果并回跳前端
*
* @author Ray.Hao
* @since 4.12.0
*/
@Slf4j
@Component
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcLoginHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler {
private final OidcProperties oidcProperties;
private final UserIdentityService userIdentityService;
private final OidcTicketService oidcTicketService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
try {
if (!(authentication.getPrincipal() instanceof OidcUser oidcUser)) {
redirect(response, Map.of("error", ResultCode.OIDC_LOGIN_FAILED.getCode()));
return;
}
String provider = oidcProperties.getProvider();
String subject = oidcUser.getSubject();
Long userId = userIdentityService.findUserId(provider, subject);
if (userId == null) {
// 用户可将 subject 交给管理员完成身份关联
redirect(response, Map.of("error", ResultCode.OIDC_ACCOUNT_NOT_BOUND.getCode(), "subject", subject));
return;
}
var context = LoginContext.oidc(provider, oidcUser.getIssuer().toString(), subject,
oidcUser.getIdToken().getTokenValue());
String ticket = oidcTicketService.issue(userId, context, request, response);
redirect(response, Map.of("ticket", ticket));
} finally {
clearAuthentication(request);
}
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
clearAuthentication(request);
log.warn("OIDC 登录失败:{}", exception.getClass().getSimpleName());
redirect(response, Map.of("error", ResultCode.OIDC_LOGIN_FAILED.getCode()));
}
/**
* 清理授权流程的临时会话,业务登录由票据兑换完成
*/
private void clearAuthentication(HttpServletRequest request) {
SecurityContextHolder.clearContext();
var session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
/**
* 回跳前端,查询参数附在路由后
*/
private void redirect(HttpServletResponse response, Map<String, String> parameters) throws IOException {
String callbackUri = oidcProperties.getFrontendCallbackUri();
if (StringUtils.isBlank(callbackUri)) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "未配置统一认证回跳地址");
return;
}
StringBuilder url = new StringBuilder(callbackUri);
// hash 路由的查询参数位于 # 后面
String route = callbackUri.substring(callbackUri.indexOf('#') + 1);
String separator = route.contains("?") ? "&" : "?";
for (var parameter : parameters.entrySet()) {
url.append(separator)
.append(parameter.getKey())
.append('=')
.append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8));
separator = "&";
}
response.sendRedirect(url.toString());
}
}
@@ -0,0 +1,12 @@
package com.youlai.boot.auth.oidc.model;
import com.youlai.boot.framework.security.session.LoginContext;
/**
* 一次性票据中的用户、外部身份与浏览器绑定摘要
*
* @author Ray.Hao
* @since 4.12.0
*/
public record OidcTicketContext(Long userId, LoginContext loginContext, String browserBinding) {
}
@@ -0,0 +1,20 @@
package com.youlai.boot.auth.oidc.model.form;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 统一认证票据兑换请求
*
* @author Ray.Hao
* @since 4.12.0
*/
@Schema(description = "统一认证票据兑换请求")
@Data
public class OidcTicketExchangeForm {
@Schema(description = "一次性交接票据")
@NotBlank(message = "票据不能为空")
private String ticket;
}
@@ -0,0 +1,23 @@
package com.youlai.boot.auth.oidc.model.form;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.Data;
/**
* 设置本地用户的 OIDC 身份;issuer 和 provider 均由服务端配置确定
*
* @author Ray.Hao
* @since 4.13.0
*/
@Data
@Schema(description = "用户的统一认证身份设置")
public class OidcUserIdentityForm {
// 认证中心实际签发的 sub,区分大小写,不能填写用户名或客户端 ID
@NotBlank(message = "subject 不能为空")
@Size(max = 255, message = "subject 长度不能超过255个字符")
@Schema(description = "ID Token 中的 sub")
private String subject;
}
@@ -0,0 +1,16 @@
package com.youlai.boot.auth.oidc.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* 当前认证中心及用户的关联;未关联时 subject 为 null
*
* @author Ray.Hao
* @since 4.13.0
*/
@Schema(description = "用户的统一认证身份")
public record OidcUserIdentityVO(
@Schema(description = "服务端配置的认证中心 issuer") String issuer,
@Schema(description = "已关联的 sub,未关联时为空") String subject
) {
}
@@ -0,0 +1,70 @@
package com.youlai.boot.auth.oidc.service;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.config.OidcProperties;
import com.youlai.boot.auth.oidc.model.OidcTicketContext;
import com.youlai.boot.common.enums.StatusEnum;
import com.youlai.boot.common.exception.TokenInvalidException;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.framework.security.model.SecurityUser;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.session.SessionService;
import com.youlai.boot.system.service.UserIdentityService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
/**
* 将 OIDC 登录票据兑换为本地会话
*
* @author Ray.Hao
* @since 4.12.0
*/
@Service
@RequiredArgsConstructor
@ConditionalOnOidcEnabled
public class OidcLoginService {
private final OidcTicketService oidcTicketService;
private final OidcProperties oidcProperties;
private final UserIdentityService userIdentityService;
private final SessionService sessionService;
/**
* 消费票据,重新核对身份关联后创建本地会话
*/
public TokenPair exchangeTicket(String ticket, HttpServletRequest request) {
OidcTicketContext ticketContext = oidcTicketService.consume(ticket, request);
var context = ticketContext.loginContext();
if (!oidcProperties.getProvider().equals(context.provider())
|| !oidcProperties.getIssuer().equals(context.issuer())) {
throw new TokenInvalidException(ResultCode.OIDC_LOGIN_FAILED);
}
// 领票后可能已解除或修改关联,不能直接沿用票据中的用户
Long currentUserId = userIdentityService.findUserId(context.provider(), context.subject());
if (!ticketContext.userId().equals(currentUserId)) {
throw new TokenInvalidException(ResultCode.OIDC_ACCOUNT_NOT_BOUND);
}
SecurityUser securityUser = userIdentityService.getAuthInfoByUserId(currentUserId);
if (securityUser == null) {
throw new TokenInvalidException(ResultCode.OIDC_ACCOUNT_NOT_BOUND);
}
if (!StatusEnum.ENABLE.getValue().equals(securityUser.getStatus())) {
throw new TokenInvalidException(ResultCode.ACCOUNT_FROZEN);
}
SecurityUserDetails userDetails = new SecurityUserDetails(securityUser);
Authentication authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
TokenPair tokenPair = sessionService.create(authentication, context);
userIdentityService.markLogin(context.provider(), context.subject());
return tokenPair;
}
}
@@ -0,0 +1,81 @@
package com.youlai.boot.auth.oidc.service;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.config.OidcClientRegistrationConfig;
import com.youlai.boot.auth.oidc.config.OidcProperties;
import com.youlai.boot.framework.security.session.LoginContext;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* 为 OIDC 登录生成认证中心登出地址
*
* @author Ray.Hao
* @since 4.12.0
*/
@Service
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcLogoutService {
private final OidcProperties oidcProperties;
private final ClientRegistrationRepository clientRegistrations;
/**
* 本地登录或提供方不支持登出时返回 null
*/
public String getLogoutUrl(LoginContext context) {
if (context.source() != LoginContext.Source.OIDC) {
return null;
}
var registration = clientRegistrations.findByRegistrationId(OidcClientRegistrationConfig.REGISTRATION_ID);
String redirectUri = getPostLogoutRedirectUri();
if (registration == null || redirectUri == null) {
return null;
}
Object endpoint = registration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint");
if (!(endpoint instanceof String logoutEndpoint) || StringUtils.isBlank(logoutEndpoint)) {
// 提供方未声明主动登出能力时,只完成本地退出
return null;
}
String separator = logoutEndpoint.contains("?") ? "&" : "?";
String logoutUrl = logoutEndpoint + separator + "post_logout_redirect_uri="
+ URLEncoder.encode(redirectUri, StandardCharsets.UTF_8);
if (StringUtils.isNotBlank(context.idToken())) {
return logoutUrl + "&id_token_hint="
+ URLEncoder.encode(context.idToken(), StandardCharsets.UTF_8);
}
if (StringUtils.isBlank(oidcProperties.getClientId())) {
return null;
}
return logoutUrl + "&client_id="
+ URLEncoder.encode(oidcProperties.getClientId(), StandardCharsets.UTF_8);
}
/**
* 登出后回跳的前端地址,取统一认证回调地址的同源根路径
*/
private String getPostLogoutRedirectUri() {
String callbackUri = oidcProperties.getFrontendCallbackUri();
if (StringUtils.isBlank(callbackUri)) {
return null;
}
URI callback = URI.create(callbackUri);
if (callback.getScheme() == null || callback.getAuthority() == null) {
return null;
}
return callback.getScheme() + "://" + callback.getAuthority() + "/";
}
}
@@ -0,0 +1,38 @@
package com.youlai.boot.auth.oidc.service;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.config.OidcProperties;
import com.youlai.boot.framework.security.session.LoginContext;
import com.youlai.boot.framework.security.session.LoginSession;
import com.youlai.boot.framework.security.session.SessionValidator;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
/**
* 检查会话所属的认证源是否仍然启用
*
* @author Ray.Hao
* @since 4.13.0
*/
@Component
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcSessionValidator implements SessionValidator {
private final OidcProperties properties;
@Override
public LoginContext.Source source() {
return LoginContext.Source.OIDC;
}
@Override
public void validate(LoginSession session) {
var context = session.context();
if (!properties.isEnabled() || !properties.getProvider().equals(context.provider())
|| !properties.getIssuer().equals(context.issuer())) {
throw new BadCredentialsException("OIDC provider is no longer available");
}
}
}
@@ -0,0 +1,115 @@
package com.youlai.boot.auth.oidc.service;
import com.youlai.boot.framework.security.token.SecureTokenGenerator;
import com.youlai.boot.framework.security.session.LoginContext;
import com.youlai.boot.auth.oidc.config.ConditionalOnOidcEnabled;
import com.youlai.boot.auth.oidc.model.OidcTicketContext;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.common.exception.TokenInvalidException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Service;
import tools.jackson.databind.json.JsonMapper;
import java.time.Duration;
import java.util.List;
/**
* 签发并消费绑定浏览器的一次性登录票据
*
* @author Ray.Hao
* @since 4.12.0
*/
@Service
@ConditionalOnOidcEnabled
@RequiredArgsConstructor
public class OidcTicketService {
public static final String BROWSER_BINDING_COOKIE = "YOULAI_OIDC_BIND";
private static final Duration TICKET_TTL = Duration.ofSeconds(45);
// 校验浏览器绑定后删除,票据只能兑换一次
private static final DefaultRedisScript<String> CONSUME = new DefaultRedisScript<>("""
local raw = redis.call('GET', KEYS[1])
if not raw then return nil end
if cjson.decode(raw).browserBinding ~= ARGV[1] then return nil end
redis.call('DEL', KEYS[1])
return raw
""", String.class);
private final StringRedisTemplate stringRedisTemplate;
private final JsonMapper jsonMapper;
/**
* 签发票据,并用 HttpOnly Cookie 绑定当前浏览器
*/
public String issue(Long userId, LoginContext loginContext,
HttpServletRequest request, HttpServletResponse response) {
String binding = SecureTokenGenerator.generate();
var context = new OidcTicketContext(userId, loginContext, SecureTokenGenerator.digest(binding));
String ticket = SecureTokenGenerator.generate();
stringRedisTemplate.opsForValue().set(getTicketKey(ticket), jsonMapper.writeValueAsString(context), TICKET_TTL);
ResponseCookie cookie = ResponseCookie.from(BROWSER_BINDING_COOKIE, binding)
.httpOnly(true)
.secure(request.isSecure())
.path("/")
.maxAge(TICKET_TTL)
.sameSite("Lax")
.build();
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
return ticket;
}
/**
* 校验浏览器绑定后原子消费票据
*/
public OidcTicketContext consume(String ticket, HttpServletRequest request) {
String binding = getBrowserBinding(request);
if (StringUtils.isBlank(ticket) || StringUtils.isBlank(binding)) {
throw new TokenInvalidException(ResultCode.OIDC_TICKET_INVALID);
}
String json = stringRedisTemplate.execute(CONSUME, List.of(getTicketKey(ticket)),
SecureTokenGenerator.digest(binding));
if (StringUtils.isBlank(json)) {
throw new TokenInvalidException(ResultCode.OIDC_TICKET_INVALID);
}
return jsonMapper.readValue(json, OidcTicketContext.class);
}
/**
* 读取用于票据校验的浏览器绑定 Cookie
*/
private String getBrowserBinding(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return null;
}
for (Cookie cookie : cookies) {
if (BROWSER_BINDING_COOKIE.equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
/**
* 通过票据摘要构造存储键
*/
private String getTicketKey(String ticket) {
return RedisConstants.Auth.OIDC_TICKET.replace("{}", SecureTokenGenerator.digest(ticket));
}
}
@@ -7,7 +7,7 @@ import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.ActionTypeEnum;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.web.ratelimit.RateLimit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -33,6 +33,9 @@ public class PasswordAuthController {
private final PasswordAuthService passwordAuthService;
/**
* 生成登录图形验证码
*/
@Operation(summary = "获取验证码")
@GetMapping("/captcha")
public Result<CaptchaVO> getCaptcha() {
@@ -40,12 +43,15 @@ public class PasswordAuthController {
return Result.success(captcha);
}
/**
* 校验账号密码并创建登录会话
*/
@Operation(summary = "账号密码登录")
@PostMapping("/login")
@Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN)
@RateLimit
public Result<AuthenticationToken> login(@RequestBody @Valid LoginForm request) {
AuthenticationToken authenticationToken = passwordAuthService.login(request.getUsername(), request.getPassword());
public Result<TokenPair> login(@RequestBody @Valid LoginForm request) {
TokenPair authenticationToken = passwordAuthService.login(request.getUsername(), request.getPassword());
return Result.success(authenticationToken);
}
@@ -1,8 +1,8 @@
package com.youlai.boot.auth.password.service;
import com.youlai.boot.auth.password.model.vo.CaptchaVO;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.token.TokenManager;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.session.SessionService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -21,7 +21,7 @@ import org.springframework.stereotype.Service;
public class PasswordAuthService {
private final AuthenticationManager authenticationManager;
private final TokenManager tokenManager;
private final SessionService sessionService;
private final CaptchaService captchaService;
/**
@@ -31,19 +31,16 @@ public class PasswordAuthService {
* @param password 密码
* @return 访问令牌
*/
public AuthenticationToken login(String username, String password) {
// 1. 创建用于密码认证的令牌(未认证)
public TokenPair login(String username, String password) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(username.trim(), password);
// 2. 执行认证(认证中)
Authentication authentication = authenticationManager.authenticate(authenticationToken);
// 3. 认证成功后生成 JWT 令牌,并存入 Security 上下文,供登录日志 AOP 使用(已认证)
AuthenticationToken authenticationTokenResponse =
tokenManager.generateToken(authentication);
TokenPair tokens = sessionService.create(authentication);
// 登录日志从安全上下文读取操作者
SecurityContextHolder.getContext().setAuthentication(authentication);
return authenticationTokenResponse;
return tokens;
}
/**
@@ -5,7 +5,7 @@ import com.youlai.boot.auth.qrcode.model.vo.QrCodeGenerateVO;
import com.youlai.boot.auth.qrcode.model.vo.QrCodeStatusVO;
import com.youlai.boot.auth.qrcode.service.QrCodeLoginService;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.util.SecurityUtils;
import com.youlai.boot.framework.web.ratelimit.RateLimit;
import com.youlai.boot.framework.web.util.IPUtils;
@@ -87,7 +87,7 @@ public class QrCodeAuthController {
*/
@Operation(summary = "[扫码]PC 端换取会话令牌")
@PostMapping("/login")
public Result<AuthenticationToken> login(@RequestBody @Valid QrCodeTicketForm form) {
public Result<TokenPair> login(@RequestBody @Valid QrCodeTicketForm form) {
return Result.success(qrCodeLoginService.login(form.getTicket()));
}
}
@@ -1,6 +1,7 @@
package com.youlai.boot.auth.qrcode.model.context;
import lombok.Data;
import lombok.ToString;
/**
* 扫码登录票据上下文,序列化为 JSON 存入 Redis
@@ -11,7 +12,8 @@ import lombok.Data;
@Data
public class QrCodeLoginContext {
// 票据,UUID 无连字符
// 票据,32 字节随机数的 Base64URL 编码
@ToString.Exclude
private String ticket;
// 状态枚举名,取 {@link com.youlai.boot.auth.qrcode.enums.QrCodeLoginStatusEnum#name()}
@@ -1,6 +1,5 @@
package com.youlai.boot.auth.qrcode.service;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.auth.qrcode.enums.QrCodeLoginStatusEnum;
import com.youlai.boot.auth.qrcode.model.context.QrCodeLoginContext;
@@ -9,19 +8,23 @@ import com.youlai.boot.auth.qrcode.model.vo.QrCodeStatusVO;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.exception.TokenInvalidException;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.model.SecurityUser;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import com.youlai.boot.framework.security.token.TokenManager;
import com.youlai.boot.system.service.UserSocialService;
import com.youlai.boot.framework.security.session.SessionService;
import com.youlai.boot.framework.security.token.SecureTokenGenerator;
import com.youlai.boot.system.service.UserIdentityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import tools.jackson.databind.json.JsonMapper;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
@@ -38,27 +41,33 @@ public class QrCodeLoginService {
// 票据默认有效期(秒)
private static final int DEFAULT_EXPIRE_SECONDS = 300;
// 状态流转时若 Redis 剩余 TTL 小于该值,补足到此值
private static final int MIN_REMAIN_SECONDS = 30;
// 状态只能单向推进,写入沿用票据剩余有效期
private static final DefaultRedisScript<Long> TRANSITION = new DefaultRedisScript<>("""
local raw = redis.call('GET', KEYS[1])
if not raw or cjson.decode(raw).status ~= ARGV[1] then return 0 end
local ttl = redis.call('PTTL', KEYS[1])
if ttl <= 0 then return 0 end
redis.call('SET', KEYS[1], ARGV[2], 'PX', ttl)
return 1
""", Long.class);
// 从 Redis 读回的值可能是不带类型信息的 Map(序列化器以 Object.class 存储),
private static final JsonMapper JSON_MAPPER = JsonMapper.builder().build();
private final RedisTemplate<String, Object> redisTemplate;
private final TokenManager tokenManager;
private final UserSocialService userSocialService;
private final StringRedisTemplate redisTemplate;
private final JsonMapper json;
private final SessionService sessionService;
private final UserIdentityService userIdentityService;
/**
* 生成扫码票据,写入 Redis 后返回 ticket 和有效期
*/
public QrCodeGenerateVO generate(String clientIp) {
String ticket = IdUtil.fastSimpleUUID();
String ticket = SecureTokenGenerator.generate();
QrCodeLoginContext ctx = new QrCodeLoginContext();
ctx.setTicket(ticket);
ctx.setStatus(QrCodeLoginStatusEnum.WAITING.name());
ctx.setCreatedAt(System.currentTimeMillis());
ctx.setClientIp(clientIp);
save(ctx, DEFAULT_EXPIRE_SECONDS);
redisTemplate.opsForValue().set(key(ticket), json.writeValueAsString(ctx),
Duration.ofSeconds(DEFAULT_EXPIRE_SECONDS));
return QrCodeGenerateVO.builder()
.ticket(ticket)
.expireSeconds(DEFAULT_EXPIRE_SECONDS)
@@ -82,7 +91,7 @@ public class QrCodeLoginService {
fillUserInfo(ctx, userId);
ctx.setStatus(QrCodeLoginStatusEnum.SCANNED.name());
ctx.setScannedAt(System.currentTimeMillis());
save(ctx, refreshTtl(ticket));
transition(ctx, QrCodeLoginStatusEnum.WAITING);
return toResp(ctx, remainingSeconds(ticket));
}
@@ -95,7 +104,7 @@ public class QrCodeLoginService {
requireSameUser(ctx, userId);
ctx.setStatus(QrCodeLoginStatusEnum.CONFIRMED.name());
ctx.setConfirmedAt(System.currentTimeMillis());
save(ctx, refreshTtl(ticket));
transition(ctx, QrCodeLoginStatusEnum.SCANNED);
return toResp(ctx, remainingSeconds(ticket));
}
@@ -116,49 +125,47 @@ public class QrCodeLoginService {
requireSameUser(ctx, userId);
}
ctx.setStatus(QrCodeLoginStatusEnum.CANCELED.name());
save(ctx, refreshTtl(ticket));
transition(ctx, current);
return toResp(ctx, remainingSeconds(ticket));
}
/**
* PC 端用票据换取会话令牌,CONFIRMED → LOGGED_IN(一次性)
*/
public AuthenticationToken login(String ticket) {
public TokenPair login(String ticket) {
QrCodeLoginContext ctx = loadOrThrow(ticket);
requireStatus(ctx, QrCodeLoginStatusEnum.CONFIRMED);
SecurityUser securityUser = userSocialService.getAuthInfoByUserId(ctx.getUserId());
SecurityUser securityUser = userIdentityService.getAuthInfoByUserId(ctx.getUserId());
if (securityUser == null) {
throw new TokenInvalidException(ResultCode.ACCOUNT_NOT_FOUND);
}
if (!Integer.valueOf(1).equals(securityUser.getStatus())) {
throw new TokenInvalidException(ResultCode.ACCOUNT_FROZEN);
}
SecurityUserDetails details = new SecurityUserDetails(securityUser);
Authentication authentication = new UsernamePasswordAuthenticationToken(
details, null, details.getAuthorities());
AuthenticationToken token = tokenManager.generateToken(authentication);
// 换取令牌成功后立即把票据置为已使用(一次性),再次 login 会在 requireStatus(CONFIRMED) 处被拒
// 先原子消费,再签发凭证,确保并发兑换最多成功一次
ctx.setStatus(QrCodeLoginStatusEnum.LOGGED_IN.name());
save(ctx, Math.max(remainingSeconds(ticket), MIN_REMAIN_SECONDS));
return token;
transition(ctx, QrCodeLoginStatusEnum.CONFIRMED);
return sessionService.create(authentication);
}
/**
* 读取票据上下文,票据为空、不存在或已过期都视为 QR_CODE_NOT_FOUND
*/
private QrCodeLoginContext loadOrThrow(String ticket) {
if (StrUtil.isBlank(ticket)) {
if (ticket == null || !ticket.matches("[A-Za-z0-9_-]{43}")) {
throw new TokenInvalidException(ResultCode.QR_CODE_NOT_FOUND);
}
Object raw = redisTemplate.opsForValue().get(key(ticket));
String raw = redisTemplate.opsForValue().get(key(ticket));
if (raw == null) {
throw new TokenInvalidException(ResultCode.QR_CODE_NOT_FOUND);
}
if (raw instanceof QrCodeLoginContext ctx) {
return ctx;
}
// 序列化器以 Object.class 存储、未带类型信息,读回来是 Map,这里再转回强类型
try {
return JSON_MAPPER.convertValue(raw, QrCodeLoginContext.class);
} catch (Exception e) {
log.error("扫码登录上下文反序列化失败, ticket={}", ticket, e);
return json.readValue(raw, QrCodeLoginContext.class);
} catch (tools.jackson.core.JacksonException exception) {
log.warn("扫码票据数据格式错误");
throw new TokenInvalidException(ResultCode.QR_CODE_NOT_FOUND);
}
}
@@ -185,7 +192,7 @@ public class QrCodeLoginService {
* 扫码时把当前 APP 用户的昵称、头像写进上下文,供 PC 端 status 展示
*/
private void fillUserInfo(QrCodeLoginContext ctx, Long userId) {
SecurityUser info = userSocialService.getAuthInfoByUserId(userId);
SecurityUser info = userIdentityService.getAuthInfoByUserId(userId);
if (info == null) {
throw new TokenInvalidException(ResultCode.ACCOUNT_NOT_FOUND);
}
@@ -195,10 +202,14 @@ public class QrCodeLoginService {
}
/**
* 重写整个上下文并刷新 TTL
* 按期望状态原子替换,保持原有截止时间
*/
private void save(QrCodeLoginContext ctx, int ttl) {
redisTemplate.opsForValue().set(key(ctx.getTicket()), ctx, ttl, TimeUnit.SECONDS);
private void transition(QrCodeLoginContext context, QrCodeLoginStatusEnum expected) {
Long changed = redisTemplate.execute(TRANSITION, List.of(key(context.getTicket())),
expected.name(), json.writeValueAsString(context));
if (!Long.valueOf(1).equals(changed)) {
throw new TokenInvalidException(ResultCode.QR_CODE_STATUS_ILLEGAL);
}
}
/**
@@ -209,14 +220,6 @@ public class QrCodeLoginService {
return ttl == null ? 0 : Math.max(ttl.intValue(), 0);
}
/**
* 状态流转时写回的 TTL:维持剩余时间,不足 MIN_REMAIN_SECONDS 则补足
*/
private int refreshTtl(String ticket) {
int remain = remainingSeconds(ticket);
return remain < MIN_REMAIN_SECONDS ? MIN_REMAIN_SECONDS : remain;
}
/**
* 上下文转前端 VO,昵称脱敏、用户信息仅在扫码后暴露
*/
@@ -257,6 +260,6 @@ public class QrCodeLoginService {
* 拼接票据在 Redis 中的完整 Key
*/
private String key(String ticket) {
return StrUtil.format(RedisConstants.Auth.QR_CODE_LOGIN, ticket);
return StrUtil.format(RedisConstants.Auth.QR_CODE_LOGIN, SecureTokenGenerator.digest(ticket));
}
}
@@ -5,15 +5,18 @@ import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.ActionTypeEnum;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
@@ -30,21 +33,43 @@ public class AuthSessionController {
private final AuthSessionService authSessionService;
/**
* 退出登录
*
* <p>普通登录只退本地;统一认证登录额外返回认证中心登出地址,由前端跳转完成中央退出
*/
@Operation(summary = "退出登录")
@DeleteMapping("/logout")
@Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGOUT)
public Result<Void> logout() {
authSessionService.logout();
return Result.success();
public Result<LogoutResult> logout() {
return Result.success(new LogoutResult(authSessionService.logout()));
}
/**
* 轮换刷新凭证并返回新令牌
*/
@Operation(summary = "刷新令牌")
@PostMapping("/refresh-token")
public Result<AuthenticationToken> refreshToken(
@Parameter(description = "刷新令牌", example = "xxx.xxx.xxx") @RequestParam String refreshToken
public Result<TokenPair> refreshToken(
@RequestBody @Valid RefreshTokenRequest request
) {
AuthenticationToken authenticationToken = authSessionService.refreshToken(refreshToken);
return Result.success(authenticationToken);
return Result.success(authSessionService.refreshToken(request.refreshToken()));
}
/**
* 刷新令牌请求
*/
public record RefreshTokenRequest(
@NotBlank(message = "刷新令牌不能为空") @Size(max = 128, message = "刷新令牌长度不合法")
@Schema(description = "刷新令牌") String refreshToken) {
}
/**
* 退出登录结果
*
* @param logoutUrl 认证中心登出地址;为空表示只退出了本地登录
*/
public record LogoutResult(String logoutUrl) {
}
}
@@ -1,45 +1,45 @@
package com.youlai.boot.auth.session.service;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.token.TokenManager;
import com.youlai.boot.framework.security.util.SecurityUtils;
import com.youlai.boot.auth.oidc.service.OidcLogoutService;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.session.AuthenticatedSession;
import com.youlai.boot.framework.security.session.SessionService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
* 登录态服务
* 登录会话的 HTTP 用例入口
*
* @author Ray.Hao
* @since 4.8.0
* @since 4.13.0
*/
@Service
@RequiredArgsConstructor
public class AuthSessionService {
private final TokenManager tokenManager;
private final SessionService sessions;
private final ObjectProvider<OidcLogoutService> oidcLogout;
/**
* 注销登录
* 先撤销本地会话,再尝试退出认证中心
*/
public void logout() {
String token = SecurityUtils.getAccessToken();
if (StrUtil.isNotBlank(token)) {
tokenManager.invalidateToken(token);
// 清除Security上下文
SecurityContextHolder.clearContext();
public String logout() {
var authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !(authentication.getDetails() instanceof AuthenticatedSession session)) {
return null;
}
sessions.revokeSession(session.id());
SecurityContextHolder.clearContext();
var logout = oidcLogout.getIfAvailable();
return logout == null ? null : logout.getLogoutUrl(session.context());
}
/**
* 刷新令牌
*
* @param refreshToken 刷新令牌
* @return 新的访问令牌
* 刷新当前登录会话
*/
public AuthenticationToken refreshToken(String refreshToken) {
return tokenManager.refreshToken(refreshToken);
public TokenPair refreshToken(String refreshToken) {
return sessions.refresh(refreshToken);
}
}
@@ -5,7 +5,7 @@ import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.ActionTypeEnum;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.web.ratelimit.RateLimit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -30,6 +30,9 @@ public class SmsAuthController {
private final SmsAuthService smsAuthService;
/**
* 发送手机登录验证码
*/
@Operation(summary = "[短信]发送登录短信验证码")
@PostMapping("/code")
@RateLimit(limit = 1, window = 60)
@@ -40,14 +43,17 @@ public class SmsAuthController {
return Result.success();
}
/**
* 校验手机验证码并创建登录会话
*/
@Operation(summary = "[短信]短信验证码登录")
@PostMapping("/login")
@Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN)
public Result<AuthenticationToken> login(
public Result<TokenPair> login(
@Parameter(description = "手机号", example = "18888888888") @RequestParam String mobile,
@Parameter(description = "验证码", example = "123456") @RequestParam String code
) {
AuthenticationToken loginResult = smsAuthService.loginBySms(mobile, code);
TokenPair loginResult = smsAuthService.loginBySms(mobile, code);
return Result.success(loginResult);
}
@@ -3,8 +3,8 @@ package com.youlai.boot.auth.sms.service;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.auth.sms.token.SmsAuthenticationToken;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.token.TokenManager;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.session.SessionService;
import com.youlai.boot.support.sms.SmsTypeEnum;
import com.youlai.boot.support.sms.service.SmsService;
import lombok.RequiredArgsConstructor;
@@ -31,7 +31,7 @@ import java.util.concurrent.TimeUnit;
public class SmsAuthService {
private final AuthenticationManager authenticationManager;
private final TokenManager tokenManager;
private final SessionService sessionService;
private final SmsService smsService;
private final RedisTemplate<String, Object> redisTemplate;
@@ -65,15 +65,13 @@ public class SmsAuthService {
* @param code 验证码
* @return 访问令牌
*/
public AuthenticationToken loginBySms(String mobile, String code) {
// 1. 创建用户短信验证码认证的令牌(未认证)
public TokenPair loginBySms(String mobile, String code) {
SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(mobile, code);
// 2. 执行认证(认证中)
Authentication authentication = authenticationManager.authenticate(smsAuthenticationToken);
// 3. 认证成功后生成 JWT 令牌,并存入 Security 上下文,供登录日志 AOP 使用(已认证)
AuthenticationToken authenticationToken = tokenManager.generateToken(authentication);
// 登录日志从安全上下文读取操作者
TokenPair authenticationToken = sessionService.create(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
return authenticationToken;
}
@@ -1,19 +1,31 @@
package com.youlai.boot.auth.wxma.config;
import lombok.Data;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
/**
* 微信小程序配置属性
*
* @author Ray.Hao
* @since 4.13.0
*/
@Data
@Component
@Validated
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {
/**
* 当前小程序的固定认证源标识;不同 AppID 使用不同标识,不能复用已有账号关联
*/
@NotBlank
@Pattern(regexp = "[a-z][a-z0-9-]{0,63}")
private String provider = "wechat-mini-main";
// 小程序 appid
private String appid;
@@ -8,7 +8,7 @@ import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.enums.ActionTypeEnum;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.web.ratelimit.RateLimit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
@@ -35,7 +35,10 @@ public class WxMaAuthController {
private final WxMaAuthService wxMaAuthService;
@Operation(summary = "[小程序]静默登录", description = "通过微信 code 登录,已绑定用户直接返回 token,未绑定用户返回 openid 需绑定手机号")
/**
* 校验微信登录凭证,返回会话或待绑定状态
*/
@Operation(summary = "[小程序]静默登录", description = "通过微信 code 登录,未关联用户返回绑定手机号标记")
@PostMapping("/silent-login")
@Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN)
@RateLimit
@@ -47,21 +50,27 @@ public class WxMaAuthController {
return Result.success(result);
}
/**
* 通过微信手机号授权完成登录
*/
@Operation(summary = "[小程序]手机号快捷登录", description = "同时使用微信 code 和手机号授权 code 登录,适用于企业认证小程序")
@PostMapping("/phone-login")
@Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN)
@RateLimit
public Result<AuthenticationToken> phoneLogin(@Valid @RequestBody WxMaPhoneLoginForm req) {
AuthenticationToken result = wxMaAuthService.phoneLogin(req.getLoginCode(), req.getPhoneCode());
public Result<TokenPair> phoneLogin(@Valid @RequestBody WxMaPhoneLoginForm req) {
TokenPair result = wxMaAuthService.phoneLogin(req.getLoginCode(), req.getPhoneCode());
return Result.success(result);
}
/**
* 校验微信身份和手机验证码后关联本地账号
*/
@Operation(summary = "[小程序]绑定手机号", description = "为静默登录用户绑定手机号,绑定成功后自动登录")
@PostMapping("/bind-mobile")
@Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN)
@RateLimit
public Result<AuthenticationToken> bindMobile(@Valid @RequestBody WxMaBindMobileForm req) {
AuthenticationToken result = wxMaAuthService.bindMobile(req.getOpenid(), req.getMobile(), req.getSmsCode());
public Result<TokenPair> bindMobile(@Valid @RequestBody WxMaBindMobileForm req) {
TokenPair result = wxMaAuthService.bindMobile(req.getLoginCode(), req.getMobile(), req.getSmsCode());
return Result.success(result);
}
}
@@ -3,28 +3,14 @@ package com.youlai.boot.auth.wxma.exception;
import org.springframework.security.core.AuthenticationException;
/**
* 微信小程序登录时手机号未绑定异常。
* 微信小程序登录时手机号未绑定异常
*
* @author Ray.Hao
* @since 3.1.0
*/
public class MobileNotBoundException extends AuthenticationException {
private final String openid;
private final String sessionKey;
public MobileNotBoundException(String openid, String sessionKey) {
public MobileNotBoundException() {
super("需要绑定手机号");
this.openid = openid;
this.sessionKey = sessionKey;
}
public String getOpenid() {
return openid;
}
public String getSessionKey() {
return sessionKey;
}
}
@@ -8,14 +8,16 @@ import lombok.Data;
* 微信小程序绑定手机号请求
*
* @author Ray.Hao
* @since 4.13.0
*/
@Schema(description = "微信小程序绑定手机号请求")
@Data
public class WxMaBindMobileForm {
@NotBlank(message = "openid 不能为空")
@Schema(description = "微信用户唯一标识", example = "oVBkZ0aYgDMDIywRdgPW8-joxXc4")
private String openid;
// 提交绑定前重新调用 wx.login,服务端据此确认 OpenID,不接受客户端指定身份
@NotBlank(message = "微信登录凭证不能为空")
@Schema(description = "wx.login 返回的一次性 code")
private String loginCode;
@NotBlank(message = "手机号不能为空")
@Schema(description = "手机号码", example = "18888888888")
@@ -5,11 +5,13 @@ import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* 微信小程序登录响应
*
* @author Ray.Hao
* @since 4.13.0
*/
@Data
@Builder
@@ -24,18 +26,17 @@ public class WxMaLoginVO {
@Schema(description = "是否需要绑定手机号")
private Boolean needBindMobile;
@Schema(description = "微信openid")
private String openid;
@Schema(description = "访问令牌")
@ToString.Exclude
private String accessToken;
@Schema(description = "刷新令牌")
@ToString.Exclude
private String refreshToken;
@Schema(description = "令牌类型")
private String tokenType;
@Schema(description = "过期时间(秒)")
private Integer expiresIn;
private Long expiresIn;
}
@@ -3,35 +3,41 @@ package com.youlai.boot.auth.wxma.provider;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.auth.wxma.exception.MobileNotBoundException;
import com.youlai.boot.auth.wxma.config.WxMaProperties;
import com.youlai.boot.auth.wxma.token.WxMaAuthenticationToken;
import com.youlai.boot.common.enums.SocialPlatformEnum;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.framework.security.model.SecurityUser;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import com.youlai.boot.framework.security.port.UserAuthenticationPort;
import com.youlai.boot.system.model.entity.UserSocial;
import com.youlai.boot.system.service.UserSocialService;
import com.youlai.boot.system.service.UserIdentityService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.concurrent.TimeUnit;
/**
* 微信小程序认证 Provider
*
* @author Ray.Hao
* @since 4.13.0
*/
@Slf4j
@RequiredArgsConstructor
public class WxMaAuthenticationProvider implements AuthenticationProvider {
private final WxMaService wxMaService;
private final WxMaProperties wxMaProperties;
private final UserAuthenticationPort userAuthPort;
private final UserSocialService userSocialService;
private final UserIdentityService userIdentityService;
private final RedisTemplate<String, Object> redisTemplate;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
@@ -49,18 +55,14 @@ public class WxMaAuthenticationProvider implements AuthenticationProvider {
log.info("微信小程序登录:openid={}", openid);
UserSocial userSocial = userSocialService.getByPlatformAndOpenid(SocialPlatformEnum.WECHAT_MINI, openid);
cacheSessionKey(openid, sessionKey);
if (userSocial == null) {
log.info("微信小程序登录:用户未绑定手机号,openid={}", openid);
throw new MobileNotBoundException(openid, sessionKey);
}
SecurityUser securityUser = userAuthPort.getAuthInfoByOpenid(SocialPlatformEnum.WECHAT_MINI, openid);
// provider 对应当前 AppID,同一个 OpenID 字符串不会跨小程序复用关联
String provider = wxMaProperties.getProvider();
SecurityUser securityUser = userAuthPort.getAuthInfoByProviderAccount(provider, openid);
if (securityUser == null) {
log.warn("微信小程序登录失败:用户不存在,openid={}", openid);
throw new UsernameNotFoundException("用户不存在");
throw new MobileNotBoundException();
}
if (ObjectUtil.notEqual(securityUser.getStatus(), 1)) {
@@ -68,9 +70,8 @@ public class WxMaAuthenticationProvider implements AuthenticationProvider {
throw new DisabledException("用户已被禁用");
}
userSocialService.updateSessionKey(userSocial.getId(), sessionKey);
SecurityUserDetails userDetails = new SecurityUserDetails(securityUser);
userIdentityService.markLogin(provider, openid);
log.info("微信小程序登录成功:username={}, openid={}", securityUser.getUsername(), openid);
return WxMaAuthenticationToken.authenticated(userDetails, userDetails.getAuthorities());
@@ -84,4 +85,18 @@ public class WxMaAuthenticationProvider implements AuthenticationProvider {
public boolean supports(Class<?> authentication) {
return WxMaAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* 会话密钥只存 Redis,不落业务库
*/
private void cacheSessionKey(String openid, String sessionKey) {
if (StrUtil.isBlank(openid) || StrUtil.isBlank(sessionKey)) {
return;
}
redisTemplate.opsForValue().set(
StrUtil.format(RedisConstants.WxMa.SESSION_KEY, wxMaProperties.getProvider(), openid),
sessionKey,
RedisConstants.WxMa.SESSION_KEY_TTL_DAYS,
TimeUnit.DAYS);
}
}
@@ -6,17 +6,17 @@ import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.auth.wxma.exception.MobileNotBoundException;
import com.youlai.boot.auth.wxma.config.WxMaProperties;
import com.youlai.boot.auth.wxma.model.vo.WxMaLoginVO;
import com.youlai.boot.auth.wxma.token.WxMaAuthenticationToken;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.enums.SocialPlatformEnum;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import com.youlai.boot.framework.security.token.TokenManager;
import com.youlai.boot.framework.security.session.SessionService;
import com.youlai.boot.system.model.entity.SysUser;
import com.youlai.boot.system.service.UserIdentityService;
import com.youlai.boot.system.service.UserRoleService;
import com.youlai.boot.system.service.UserService;
import com.youlai.boot.system.service.UserSocialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
@@ -29,6 +29,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
/**
* 微信小程序认证服务
@@ -42,10 +43,11 @@ import java.util.Collections;
public class WxMaAuthService {
private final WxMaService wxMaService;
private final WxMaProperties wxMaProperties;
private final AuthenticationManager authenticationManager;
private final TokenManager tokenManager;
private final SessionService sessionService;
private final UserService userService;
private final UserSocialService userSocialService;
private final UserIdentityService userIdentityService;
private final UserRoleService userRoleService;
private final RedisTemplate<String, Object> redisTemplate;
@@ -53,28 +55,27 @@ public class WxMaAuthService {
* 静默登录
*
* @param code 微信登录凭证(wx.login 获取)
* @return 登录结果(成功返回 token,需绑定返回 openid)
* @return 已关联时返回令牌,否则返回需绑定手机号的标记
*/
public WxMaLoginVO silentLogin(String code) {
WxMaAuthenticationToken token = new WxMaAuthenticationToken(code);
try {
Authentication authentication = authenticationManager.authenticate(token);
AuthenticationToken authToken = tokenManager.generateToken(authentication);
TokenPair authToken = sessionService.create(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
return WxMaLoginVO.builder()
.isNewUser(false)
.needBindMobile(false)
.accessToken(authToken.getAccessToken())
.refreshToken(authToken.getRefreshToken())
.tokenType(authToken.getTokenType())
.expiresIn(authToken.getExpiresIn())
.accessToken(authToken.accessToken())
.refreshToken(authToken.refreshToken())
.tokenType(authToken.tokenType())
.expiresIn(authToken.expiresIn())
.build();
} catch (MobileNotBoundException e) {
return WxMaLoginVO.builder()
.isNewUser(true)
.needBindMobile(true)
.openid(e.getOpenid())
.build();
}
}
@@ -87,7 +88,7 @@ public class WxMaAuthService {
* @return 认证令牌
*/
@Transactional(rollbackFor = Exception.class)
public AuthenticationToken phoneLogin(String loginCode, String phoneCode) {
public TokenPair phoneLogin(String loginCode, String phoneCode) {
// 1. 解析微信登录凭证,获取会话信息
WxMaJscode2SessionResult session = resolveSession(loginCode);
String openid = session.getOpenid();
@@ -110,13 +111,15 @@ public class WxMaAuthService {
/**
* 绑定手机号
*
* @param openid 微信用户唯一标识
* @param loginCode 提交绑定前重新获取的微信一次性登录凭证
* @param mobile 手机号码
* @param smsCode 短信验证码
* @return 认证令牌
*/
@Transactional(rollbackFor = Exception.class)
public AuthenticationToken bindMobile(String openid, String mobile, String smsCode) {
public TokenPair bindMobile(String loginCode, String mobile, String smsCode) {
// OpenID 只从微信接口取得,不能把前端提交的一串 ID 当成身份确认
WxMaJscode2SessionResult session = resolveSession(loginCode);
// 1. 验证短信验证码
validateSmsCode(mobile, smsCode);
@@ -124,14 +127,9 @@ public class WxMaAuthService {
SysUser user = findOrCreateUser(mobile);
// 3. 绑定微信 openid
userSocialService.bindOrUpdate(
user.getId(),
SocialPlatformEnum.WECHAT_MINI,
openid,
null, null, null, null
);
bindWechatOpenid(user, session);
log.info("微信小程序绑定手机号成功:mobile={}, openid={}", mobile, openid);
log.info("微信小程序绑定手机号成功:userId={}", user.getId());
// 4. 生成认证令牌
return generateAuthToken(mobile);
@@ -146,7 +144,7 @@ public class WxMaAuthService {
try {
return wxMaService.jsCode2SessionInfo(loginCode);
} catch (Exception e) {
log.error("获取微信会话信息失败,loginCode={}", loginCode, e);
log.error("获取微信会话信息失败", e);
throw new IllegalArgumentException("微信登录失败:" + e.getMessage());
}
}
@@ -159,7 +157,7 @@ public class WxMaAuthService {
WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(phoneCode);
return phoneInfo.getPhoneNumber();
} catch (Exception e) {
log.error("获取微信手机号失败,phoneCode={}", phoneCode, e);
log.error("获取微信手机号失败", e);
throw new IllegalArgumentException("获取手机号失败:" + e.getMessage());
}
}
@@ -195,7 +193,7 @@ public class WxMaAuthService {
userService.save(user);
// 分配 GUEST 角色(角色ID=3)
userRoleService.saveUserRoles(user.getId(), Collections.singletonList(3L));
userRoleService.replaceUserRoles(user.getId(), Collections.singletonList(3L));
return user;
}
@@ -204,20 +202,24 @@ public class WxMaAuthService {
* 绑定微信 openid
*/
private void bindWechatOpenid(SysUser user, WxMaJscode2SessionResult session) {
try {
userSocialService.bindOrUpdate(
user.getId(),
SocialPlatformEnum.WECHAT_MINI,
session.getOpenid(),
session.getUnionid(),
user.getNickname(),
user.getAvatar(),
session.getSessionKey()
);
} catch (Exception e) {
// 绑定失败不影响登录
log.warn("绑定微信 openid 失败,userId={}, openid={}", user.getId(), session.getOpenid(), e);
// 冲突必须回滚本次用户创建和关联,不能吞掉失败后继续签发令牌
userIdentityService.bindIdentity(user.getId(), wxMaProperties.getProvider(), session.getOpenid());
cacheSessionKey(session.getOpenid(), session.getSessionKey());
userIdentityService.markLogin(wxMaProperties.getProvider(), session.getOpenid());
}
/**
* 缓存微信会话密钥,供后续解密类接口使用;数据库不再保存该凭证
*/
private void cacheSessionKey(String openid, String sessionKey) {
if (StrUtil.isBlank(openid) || StrUtil.isBlank(sessionKey)) {
return;
}
redisTemplate.opsForValue().set(
StrUtil.format(RedisConstants.WxMa.SESSION_KEY, wxMaProperties.getProvider(), openid),
sessionKey,
RedisConstants.WxMa.SESSION_KEY_TTL_DAYS,
TimeUnit.DAYS);
}
/**
@@ -238,12 +240,12 @@ public class WxMaAuthService {
/**
* 生成认证令牌
*/
private AuthenticationToken generateAuthToken(String mobile) {
private TokenPair generateAuthToken(String mobile) {
SecurityUserDetails userDetails = new SecurityUserDetails(userService.getAuthInfoByMobile(mobile));
Authentication authentication = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities()
);
AuthenticationToken authToken = tokenManager.generateToken(authentication);
TokenPair authToken = sessionService.create(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
return authToken;
}
@@ -1,29 +0,0 @@
package com.youlai.boot.codegen.model.query;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.youlai.boot.common.base.BaseQuery;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* 数据表分页查询对象
*
* @author Ray
* @since 2.10.0
*/
@Schema(description = "数据表分页查询对象")
@Getter
@Setter
public class TablePageQuery extends BaseQuery {
@Schema(description="关键字(表名)")
private String keywords;
// 排除的表名
@JsonIgnore
private List<String> excludeTables;
}
@@ -9,12 +9,12 @@ import lombok.Setter;
import java.util.List;
/**
* 数据表查询对象
* 数据表分页查询对象
*
* @author Ray
* @since 2.10.0
*/
@Schema(description = "数据表查询对象")
@Schema(description = "数据表分页查询对象")
@Getter
@Setter
public class TableQuery extends BaseQuery {
@@ -36,7 +36,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 代码生成服务实现类。
* 代码生成服务实现类
*
* @author Ray
* @since 2.10.0
@@ -201,7 +201,7 @@ public class CodegenServiceImpl implements CodegenService {
}
/**
* 生成文件名。
* 生成文件名
*
* @param entityName 实体名(例如 User)
* @param templateName 模板名(例如 Entity、Controller、API)
@@ -224,7 +224,7 @@ public class CodegenServiceImpl implements CodegenService {
}
/**
* 生成文件路径。
* 生成文件路径
*
* @param templateName 模板名
* @param moduleName 模块名(例如 system)
@@ -281,9 +281,10 @@ public class CodegenServiceImpl implements CodegenService {
}
/**
* 渲染模板,生成代码内容。
* 渲染模板,生成代码内容
*
* @param templateConfig 模板配置
* @param templatePath 模板路径
* @param subpackageName 生成模型所属子包
* @param genTable 表生成配置
* @param fieldConfigs 字段配置
* @param pageType 前端页面类型
@@ -316,9 +317,12 @@ public class CodegenServiceImpl implements CodegenService {
bindMap.put("entityComment", genTable.getBusinessName());
bindMap.put("fieldConfigs", fieldConfigs);
boolean hasLocalDate = false;
boolean hasLocalDateTime = false;
boolean hasBigDecimal = false;
boolean hasRequiredField = false;
boolean hasNotBlank = false;
boolean hasNotNull = false;
boolean hasSize = false;
for (GenTableColumn fieldConfig : fieldConfigs) {
@@ -326,21 +330,37 @@ public class CodegenServiceImpl implements CodegenService {
fieldConfig.setFieldType(JavaTypeEnum.getJavaTypeByColumnType(fieldConfig.getColumnType()));
}
if ("LocalDateTime".equals(fieldConfig.getFieldType()) || "LocalDate".equals(fieldConfig.getFieldType())) {
if ("LocalDate".equals(fieldConfig.getFieldType())) {
hasLocalDate = true;
}
if ("LocalDateTime".equals(fieldConfig.getFieldType())) {
hasLocalDateTime = true;
}
if ("BigDecimal".equals(fieldConfig.getFieldType())) {
hasBigDecimal = true;
}
if (ObjectUtil.equals(fieldConfig.getIsRequired(), 1)) {
hasRequiredField = true;
if (ObjectUtil.equals(fieldConfig.getIsShowInForm(), 1) && !"id".equals(fieldConfig.getFieldName())) {
boolean isString = "String".equals(fieldConfig.getFieldType());
if (ObjectUtil.equals(fieldConfig.getIsRequired(), 1)) {
if (isString) {
hasNotBlank = true;
} else {
hasNotNull = true;
}
}
if (isString && fieldConfig.getMaxLength() != null && fieldConfig.getMaxLength() > 0) {
hasSize = true;
}
}
fieldConfig.setTsType(JavaTypeEnum.getTsTypeByJavaType(fieldConfig.getFieldType()));
}
bindMap.put("hasLocalDate", hasLocalDate);
bindMap.put("hasLocalDateTime", hasLocalDateTime);
bindMap.put("hasBigDecimal", hasBigDecimal);
bindMap.put("hasRequiredField", hasRequiredField);
bindMap.put("hasNotBlank", hasNotBlank);
bindMap.put("hasNotNull", hasNotNull);
bindMap.put("hasSize", hasSize);
TemplateEngine templateEngine = TemplateUtil.createEngine(new TemplateConfig("codegen", TemplateConfig.ResourceMode.CLASSPATH));
// 根据 ui 选择不同的前端页面模板:默认 index.vue.vm;封装版使用 index.crud.vue.vm
@@ -358,7 +378,7 @@ public class CodegenServiceImpl implements CodegenService {
}
/**
* 下载代码。
* 下载代码
*
* @param tableNames 表名数组,支持多张表
* @param ui 页面类型
@@ -384,7 +404,7 @@ public class CodegenServiceImpl implements CodegenService {
}
/**
* 根据表名生成代码并压缩到 zip 文件中。
* 根据表名生成代码并压缩到 zip 文件中
*
* @param tableName 表名
* @param zip 压缩文件输出流
@@ -243,9 +243,7 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
}
}
//---------------------------------------------------
// AI 辅助:未开启 AI 时调用返回业务异常
//---------------------------------------------------
// AI 未启用时返回业务异常
/**
* 用 AI 推断代码生成配置
@@ -1,6 +1,5 @@
package com.youlai.boot.common.base;
import com.youlai.boot.common.annotation.ValidField;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
@@ -31,14 +30,6 @@ public class BaseQuery implements Serializable {
@Max(value = 200, message = "每页记录数不能超过 200")
private Integer pageSize = 10;
@Schema(description = "排序字段", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@ValidField(allowedValues = {"create_time", "update_time"})
private String sortBy;
@Schema(description = "排序方式(正序:asc;反序:desc,不区分大小写)", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
@ValidField(allowedValues = {"asc", "desc", "ASC", "DESC"})
private String order;
public boolean isPaged() {
return pageNum != null && pageSize != null && pageSize > 0;
}
@@ -1,29 +0,0 @@
package com.youlai.boot.common.constant;
/**
* JWT Claims声明常量
*
* @author haoxr
* @since 2023/11/24
*/
public interface JwtClaimConstants {
// 令牌类型
String TOKEN_TYPE = "tokenType";
// 用户ID
String USER_ID = "userId";
// 部门ID
String DEPT_ID = "deptId";
// 数据权限列表
String DATA_SCOPES = "dataScopes";
// 角色编码集合(不带 ROLE_ 前缀)
String ROLES = "roles";
// Token 版本号
String TOKEN_VERSION = "tokenVersion";
}
@@ -30,21 +30,19 @@ public interface RedisConstants {
* 认证模块
*/
interface Auth {
// 存储访问令牌对应的用户会话信息(accessToken -> UserSession)
String ACCESS_TOKEN_USER = "auth:token:access:{}";
// 存储刷新令牌对应的用户会话信息(refreshToken -> UserSession)
String REFRESH_TOKEN_USER = "auth:token:refresh:{}";
// 用户与访问令牌的映射(userId -> accessToken)
String USER_ACCESS_TOKEN = "auth:user:access:{}";
// 用户与刷新令牌的映射(userId -> refreshToken))
String USER_REFRESH_TOKEN = "auth:user:refresh:{}";
// 已撤销 Token 的 JTI(单端退出/会话注销):如果 jti 在撤销列表中,则 Token 立即无效
String BLACKLIST_TOKEN = "auth:token:blacklist:{}";
String REVOKED_JTI = BLACKLIST_TOKEN;
// 用户 Token 版本号(用于按用户失效历史 JWT):token.tokenVersion != redis.tokenVersion => token 无效
String USER_TOKEN_VERSION = "auth:user:token_version:{}";
// 扫码登录票据上下文(ticket -> QrCodeLoginContext)
String QR_CODE_LOGIN = "auth:qr_code:{}";
String QR_CODE_LOGIN = "auth:qr_code:v2:{}";
// 统一认证一次性交接票据(ticket -> OidcTicketContext)
String OIDC_TICKET = "auth:oidc:ticket:v2:{}";
}
/**
* 微信小程序模块
*/
interface WxMa {
// 微信会话密钥(provider + OpenID -> session_key),不同小程序分别存储
String SESSION_KEY = "auth:wxma:session_key:{}:{}";
long SESSION_KEY_TTL_DAYS = 3;
}
/**
@@ -1,33 +0,0 @@
package com.youlai.boot.common.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.youlai.boot.common.base.IBaseEnum;
import lombok.Getter;
/**
* 第三方登录平台类型枚举。
*
* @author Ray.Hao
* @since 2.17.0
*/
@Getter
public enum SocialPlatformEnum implements IBaseEnum<String> {
WECHAT_MINI("WECHAT_MINI", "微信小程序"),
WECHAT_MP("WECHAT_MP", "微信公众号"),
WECHAT_OPEN("WECHAT_OPEN", "微信开放平台"),
ALIPAY("ALIPAY", "支付宝"),
QQ("QQ", "QQ"),
APPLE("APPLE", "Apple ID");
@EnumValue
private final String value;
private final String label;
SocialPlatformEnum(String value, String label) {
this.value = value;
this.label = label;
}
}
@@ -12,67 +12,74 @@ public enum ResultCode implements IResultCode, Serializable {
SUCCESS("00000", "成功"),
/** 一级宏观错误码:用户端错误(由客户端输入/认证/权限/请求方式等引起,需客户端配合修正) */
// 一级宏观错误码:用户端错误(由客户端输入/认证/权限/请求方式等引起,需客户端配合修正)
USER_ERROR("A0001", "用户端错误"),
/** 二级宏观错误码:用户端具体错误(按号段细分,便于定位是注册/登录/令牌/参数/防重等问题) */
// 二级宏观错误码:用户端具体错误(按号段细分,便于定位是注册/登录/令牌/参数/防重等问题)
/** A01xx:用户注册错误 */
// A01xx:用户注册错误
USER_REGISTRATION_ERROR("A0100", "用户注册错误"),
USER_NOT_AGREE_PRIVACY_AGREEMENT("A0101", "用户未同意隐私协议"),
/** A013x:校验码输入错误 */
// A013x:校验码输入错误
VERIFICATION_CODE_INPUT_ERROR("A0130", "校验码输入错误"),
/** A02xx:用户登录异常 */
// A02xx:用户登录异常
USER_LOGIN_EXCEPTION("A0200", "用户登录异常"),
ACCOUNT_NOT_FOUND("A0201", "用户账户不存在"),
ACCOUNT_FROZEN("A0202", "用户账户被冻结"),
USER_PASSWORD_ERROR("A0210", "用户名或密码错误"),
/** A023x:令牌无效或已过期 */
// A023x:令牌无效或已过期
ACCESS_TOKEN_INVALID("A0230", "访问令牌无效或已过期"),
REFRESH_TOKEN_INVALID("A0231", "刷新令牌无效或已过期"),
/** A024x:验证码错误 */
// A024x:验证码错误
USER_VERIFICATION_CODE_ERROR("A0240", "验证码错误"),
USER_VERIFICATION_CODE_ATTEMPT_LIMIT_EXCEEDED("A0241", "用户验证码尝试次数超限"),
USER_VERIFICATION_CODE_EXPIRED("A0242", "用户验证码过期"),
/** A025x:扫码登录异常 */
// A025x:扫码登录异常
QR_CODE_NOT_FOUND("A0250", "扫码登录票据不存在或已过期"),
QR_CODE_STATUS_ILLEGAL("A0251", "当前扫码状态不允许该操作"),
QR_CODE_USER_MISMATCH("A0252", "操作用户与扫码用户不一致"),
QR_CODE_ALREADY_USED("A0253", "扫码登录票据已被使用"),
/** A03xx:访问权限异常 */
// A026x:统一认证登录异常
OIDC_TICKET_INVALID("A0260", "统一认证登录票据无效或已过期"),
OIDC_ACCOUNT_NOT_BOUND("A0262", "该统一认证账号尚未开通业务账号,请联系管理员"),
OIDC_LOGIN_FAILED("A0264", "统一认证登录失败"),
// A03xx:访问权限异常
ACCESS_PERMISSION_EXCEPTION("A0300", "访问权限异常"),
ACCESS_UNAUTHORIZED("A0301", "访问未授权"),
/** A04xx:用户请求参数错误 */
// A04xx:用户请求参数错误
USER_REQUEST_PARAMETER_ERROR("A0400", "用户请求参数错误"),
INVALID_USER_INPUT("A0402", "无效的用户输入"),
REQUEST_REQUIRED_PARAMETER_IS_EMPTY("A0410", "请求必填参数为空"),
PARAMETER_FORMAT_MISMATCH("A0421", "参数格式不匹配"),
/** A05xx:用户请求服务异常 */
// A05xx:用户请求服务异常
USER_REQUEST_SERVICE_EXCEPTION("A0500", "用户请求服务异常"),
REQUEST_CONCURRENCY_LIMIT_EXCEEDED("A0502", "请求并发数超出限制"),
DUPLICATE_SUBMISSION("A0506", "请勿重复提交"),
/** A07xx:文件处理异常 */
// A07xx:文件处理异常
UPLOAD_FILE_EXCEPTION("A0700", "上传文件异常"),
DELETE_FILE_EXCEPTION("A0710", "删除文件异常"),
/** 一级宏观错误码:系统端错误(服务端内部异常/超时/不可用等,需后端排查修复) */
// 一级宏观错误码:系统端错误(服务端内部异常/超时/不可用等,需后端排查修复)
SYSTEM_ERROR("B0001", "系统执行出错"),
/** 二级宏观错误码:系统端具体错误(按号段细分,便于定位超时/限流/资源耗尽等) */
// 二级宏观错误码:系统端具体错误(按号段细分,便于定位超时/限流/资源耗尽等)
SYSTEM_EXECUTION_TIMEOUT("B0100", "系统执行超时"),
AUTH_SERVICE_UNAVAILABLE("B0101", "认证服务暂不可用,请稍后重试"),
REALTIME_DISABLED("B0102", "实时通信未启用"),
/** 一级宏观错误码:第三方服务错误(外部依赖/中间件/数据库等引起,需检查依赖健康与配置) */
// 一级宏观错误码:第三方服务错误(外部依赖/中间件/数据库等引起,需检查依赖健康与配置)
THIRD_PARTY_SERVICE_ERROR("C0001", "调用第三方服务出错"),
/** 二级宏观错误码:第三方服务具体错误(按号段细分,便于定位是接口不存在/数据库异常等) */
// 二级宏观错误码:第三方服务具体错误(按号段细分,便于定位是接口不存在/数据库异常等)
INTERFACE_NOT_EXIST("C0113", "接口不存在"),
DATABASE_SERVICE_ERROR("C0300", "数据库服务出错"),
DATABASE_EXECUTION_ERROR("C0310", "数据库执行异常"),
@@ -1,5 +1,6 @@
package com.youlai.boot.config;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tools.jackson.databind.cfg.DateTimeFeature;
@@ -9,6 +10,7 @@ import tools.jackson.databind.ser.std.ToStringSerializer;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.TimeZone;
/**
@@ -20,6 +22,9 @@ import java.util.TimeZone;
@Configuration
public class JacksonConfig {
// 默认日期时间格式,Date 与 LocalDateTime 共用
private static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 全局 JsonMapper
*/
@@ -27,8 +32,11 @@ public class JacksonConfig {
public JsonMapper objectMapper() {
return JsonMapper.builder()
.disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS)
.defaultDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
.defaultDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_PATTERN))
.defaultTimeZone(TimeZone.getTimeZone("GMT+8"))
// LocalDateTime 没有全局格式开关,按类型覆盖默认格式;字段上的 @JsonFormat 仍优先
.withConfigOverride(LocalDateTime.class,
override -> override.setFormat(JsonFormat.Value.forPattern(DEFAULT_DATE_TIME_PATTERN)))
.addModule(new SimpleModule()
.addSerializer(Long.class, ToStringSerializer.instance)
.addSerializer(BigInteger.class, ToStringSerializer.instance)
@@ -1,150 +0,0 @@
package com.youlai.boot.config;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.github.xiaoymin.knife4j.core.conf.ExtensionsConstants;
import com.github.xiaoymin.knife4j.core.conf.GlobalConstants;
import com.github.xiaoymin.knife4j.spring.configuration.Knife4jProperties;
import com.github.xiaoymin.knife4j.spring.configuration.Knife4jSetting;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.models.OpenAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.properties.SpringDocConfigProperties;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestController;
import java.lang.annotation.Annotation;
import java.util.*;
import java.util.stream.Collectors;
/**
* 增强扩展属性支持
* @since 4.1.0
* @author <a href="xiaoymin@foxmail.com">xiaoymin@foxmail.com</a>
* 2022/12/11 22:40
*/
@Primary
@Configuration
@Slf4j
public class Knife4jOpenApiCustomizer extends com.github.xiaoymin.knife4j.spring.extension.Knife4jOpenApiCustomizer implements GlobalOpenApiCustomizer {
final Knife4jProperties knife4jProperties;
final SpringDocConfigProperties properties;
public Knife4jOpenApiCustomizer(Knife4jProperties knife4jProperties, SpringDocConfigProperties properties) {
super(knife4jProperties,properties);
this.knife4jProperties = knife4jProperties;
this.properties = properties;
}
@Override
public void customise(OpenAPI openApi) {
log.debug("Knife4j OpenApiCustomizer");
if (knife4jProperties.isEnable()) {
Knife4jSetting setting = knife4jProperties.getSetting();
OpenApiExtensionResolver openApiExtensionResolver = new OpenApiExtensionResolver(setting, knife4jProperties.getDocuments());
// 解析初始化
openApiExtensionResolver.start();
Map<String, Object> objectMap = new HashMap<>();
objectMap.put(GlobalConstants.EXTENSION_OPEN_SETTING_NAME, setting);
objectMap.put(GlobalConstants.EXTENSION_OPEN_MARKDOWN_NAME, openApiExtensionResolver.getMarkdownFiles());
openApi.addExtension(GlobalConstants.EXTENSION_OPEN_API_NAME, objectMap);
addOrderExtension(openApi);
}
}
/**
* 往OpenAPI内tags字段添加x-order属性
*
* @param openApi openApi
*/
private void addOrderExtension(OpenAPI openApi) {
if (CollectionUtils.isEmpty(properties.getGroupConfigs())) {
return;
}
// 获取包扫描路径
Set<String> packagesToScan =
properties.getGroupConfigs().stream()
.map(SpringDocConfigProperties.GroupConfig::getPackagesToScan)
.filter(toScan -> !CollectionUtils.isEmpty(toScan))
.flatMap(List::stream)
.collect(Collectors.toSet());
if (CollectionUtils.isEmpty(packagesToScan)) {
return;
}
// 扫描包下被ApiSupport注解的RestController Class
Set<Class<?>> classes =
packagesToScan.stream()
.map(packageToScan -> scanPackageByAnnotation(packageToScan, RestController.class))
.flatMap(Set::stream)
.filter(clazz -> clazz.isAnnotationPresent(ApiSupport.class))
.collect(Collectors.toSet());
if (!CollectionUtils.isEmpty(classes)) {
// ApiSupport oder值存入tagSortMap<Tag.name,ApiSupport.order>
Map<String, Integer> tagOrderMap = new HashMap<>();
classes.forEach(
clazz -> {
Tag tag = getTag(clazz);
if (Objects.nonNull(tag)) {
ApiSupport apiSupport = clazz.getAnnotation(ApiSupport.class);
tagOrderMap.putIfAbsent(tag.name(), apiSupport.order());
}
});
// 往openApi tags字段添加x-order增强属性
if (openApi.getTags() != null) {
openApi
.getTags()
.forEach(
tag -> {
if (tagOrderMap.containsKey(tag.getName())) {
tag.addExtension(
ExtensionsConstants.EXTENSION_ORDER, tagOrderMap.get(tag.getName()));
}
});
}
}
}
private Tag getTag(Class<?> clazz) {
// 从类上获取
Tag tag = clazz.getAnnotation(Tag.class);
if (Objects.isNull(tag)) {
// 从接口上获取
Class<?>[] interfaces = clazz.getInterfaces();
if (ArrayUtils.isNotEmpty(interfaces)) {
for (Class<?> interfaceClazz : interfaces) {
Tag anno = interfaceClazz.getAnnotation(Tag.class);
if (Objects.nonNull(anno)) {
tag = anno;
break;
}
}
}
}
return tag;
}
private Set<Class<?>> scanPackageByAnnotation(
String packageName, final Class<? extends Annotation> annotationClass) {
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClass));
Set<Class<?>> classes = new HashSet<>();
for (BeanDefinition beanDefinition : scanner.findCandidateComponents(packageName)) {
try {
Class<?> clazz = Class.forName(beanDefinition.getBeanClassName());
classes.add(clazz);
} catch (ClassNotFoundException ignore) {
}
}
return classes;
}
}
@@ -24,7 +24,7 @@ import java.util.stream.Stream;
* OpenAPI 接口文档配置
*
* @author Ray.Hao
* @see <a href="https://doc.xiaominfo.com/docs/quick-start">knife4j 快速开始</a>
* @see <a href="https://springdoc.org/">springdoc 文档</a>
* @since 2023/2/17
*/
@Configuration
@@ -4,16 +4,16 @@ import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.ArrayUtil;
import com.youlai.boot.auth.password.service.CaptchaService;
import com.youlai.boot.framework.security.config.SecurityProperties;
import com.youlai.boot.framework.security.filter.TokenAuthenticationFilter;
import com.youlai.boot.framework.security.handler.JsonAccessDeniedHandler;
import com.youlai.boot.framework.security.handler.JsonAuthenticationEntryPoint;
import com.youlai.boot.framework.security.port.UserAuthenticationPort;
import com.youlai.boot.framework.security.service.SecurityUserDetailsService;
import com.youlai.boot.framework.security.token.TokenManager;
import com.youlai.boot.framework.security.session.SessionService;
import com.youlai.boot.auth.password.filter.CaptchaValidationFilter;
import com.youlai.boot.auth.sms.provider.SmsAuthenticationProvider;
import com.youlai.boot.auth.wxma.provider.WxMaAuthenticationProvider;
import com.youlai.boot.system.service.UserSocialService;
import com.youlai.boot.auth.wxma.config.WxMaProperties;
import com.youlai.boot.system.service.UserIdentityService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -21,18 +21,22 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.ObjectPostProcessor;
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
import org.springframework.security.web.authentication.AuthenticationEntryPointFailureHandler;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import jakarta.servlet.DispatcherType;
import org.springframework.http.HttpMethod;
/**
* Spring Security 配置类
@@ -48,17 +52,19 @@ public class SecurityConfig {
private final RedisTemplate<String, Object> redisTemplate;
private final PasswordEncoder passwordEncoder;
private final TokenManager tokenManager;
private final SessionService sessionService;
private final SecurityUserDetailsService userDetailsService;
private final CaptchaService captchaService;
private final SecurityProperties securityProperties;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
http
.authorizeHttpRequests(requestMatcherRegistry -> {
// ASYNC 分发(SSE 超时/完成后的异步 dispatch)无 Authorization 头,直接放行
// 异步响应的后续分发复用首次请求认证结果
requestMatcherRegistry.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll();
// 握手使用一次性票据;其余实时接口仍需 Bearer 认证
requestMatcherRegistry.requestMatchers(HttpMethod.GET, "/api/v1/realtime/ws").permitAll();
String[] permitAllUrls = securityProperties.getPermitAllUrls();
if (ArrayUtil.isNotEmpty(permitAllUrls)) {
requestMatcherRegistry.requestMatchers(permitAllUrls).permitAll();
@@ -78,11 +84,26 @@ public class SecurityConfig {
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
// 验证码校验(使用方过滤器,直接写 JSON 响应)
.addFilterBefore(new CaptchaValidationFilter(captchaService), UsernamePasswordAuthenticationFilter.class)
// Token 认证(Starter 过滤器,抛 AuthenticationException 交给 ExceptionTranslationFilter 处理)
.addFilterBefore(new TokenAuthenticationFilter(tokenManager), AuthorizationFilter.class)
.build();
.oauth2ResourceServer(resource -> resource
.authenticationManagerResolver(request -> authentication -> {
var bearer = (BearerTokenAuthenticationToken) authentication;
return sessionService.authenticate(bearer.getToken()).toAuthentication();
})
.authenticationEntryPoint(new JsonAuthenticationEntryPoint())
.withObjectPostProcessor(new ObjectPostProcessor<BearerTokenAuthenticationFilter>() {
@Override
public <O extends BearerTokenAuthenticationFilter> O postProcess(O filter) {
var failureHandler = new AuthenticationEntryPointFailureHandler(new JsonAuthenticationEntryPoint());
// 存储故障返回 JSON 503,不交给容器生成错误页
failureHandler.setRethrowAuthenticationServiceException(false);
filter.setAuthenticationFailureHandler(failureHandler);
return filter;
}
})
.accessDeniedHandler(new JsonAccessDeniedHandler()));
return http.build();
}
@Bean
@@ -100,10 +121,12 @@ public class SecurityConfig {
@Bean
public WxMaAuthenticationProvider wechatMiniAuthenticationProvider(
WxMaService wxMaService,
WxMaProperties wxMaProperties,
UserAuthenticationPort userAuthenticationPort,
UserSocialService userSocialService
UserIdentityService userIdentityService
) {
return new WxMaAuthenticationProvider(wxMaService, userAuthenticationPort, userSocialService);
return new WxMaAuthenticationProvider(wxMaService, wxMaProperties, userAuthenticationPort,
userIdentityService, redisTemplate);
}
@Bean
@@ -0,0 +1,53 @@
package com.youlai.boot.framework.mybatis;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 将公开排序属性转换为资源允许的数据库列
*
* @author Ray.Hao
* @since 4.13.0
*/
public final class QuerySort {
private static final int MAX_SORT_ITEMS = 3;
private QuerySort() {
}
/**
* 按输入顺序解析排序;未提供时返回空列表,由资源决定默认顺序
*/
public static List<OrderItem> parse(String[] expressions, Map<String, String> fields) {
List<OrderItem> orders = new ArrayList<>();
if (expressions == null) {
return orders;
}
if (expressions.length == 0 || expressions.length > MAX_SORT_ITEMS) {
throw new IllegalArgumentException("排序规则应为 1 至 3 项");
}
Set<String> seen = new HashSet<>();
for (String expression : expressions) {
String[] parts = expression == null ? new String[0] : expression.split(",", -1);
if (parts.length != 2 || !("asc".equals(parts[1]) || "desc".equals(parts[1]))) {
throw new IllegalArgumentException("排序格式应为 字段,asc 或 字段,desc");
}
String field = parts[0];
String column = fields.get(field);
if (column == null) {
throw new IllegalArgumentException("不支持的排序字段:" + field);
}
if (!seen.add(field)) {
throw new IllegalArgumentException("排序字段重复:" + field);
}
orders.add("asc".equals(parts[1]) ? OrderItem.asc(column) : OrderItem.desc(column));
}
return orders;
}
}
@@ -1,20 +1,23 @@
package com.youlai.boot.framework.security.config;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
/**
* 安全模块配置属性类
* 安全配置;未选中的令牌策略不要求提供配置
*
* @author Ray.Hao
* @since 2024/4/18
* @since 4.13.0
*/
@Data
@Validated
@@ -22,58 +25,60 @@ import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "security")
public class SecurityProperties {
// 令牌策略配置
@Valid
@NotNull(message = "令牌策略配置不能为空")
private TokenConfig token;
@NotNull
private TokenConfig token = new TokenConfig();
// 匿名放行路径(仍经过安全过滤器链,仅跳过认证与授权判断,保留安全响应头)
// 匿名路径仍经过安全过滤器链
@NotEmpty
private String[] permitAllUrls;
/**
* 令牌策略嵌套类
* 访问令牌与会话期限配置
*/
@Data
public static class TokenConfig {
// 令牌策略类型
@NotNull(message = "令牌类型不能为空")
@NotNull
@Pattern(regexp = "jwt|redis-token", message = "令牌类型只能是 jwt 或 redis-token")
private String type;
private String type = "jwt";
// 访问令牌有效期(单位:秒)
@Min(-1)
private Integer accessTokenTimeToLive = 3600;
@NotNull
private Duration accessTokenTimeToLive = Duration.ofHours(2);
// 刷新令牌有效期(单位:秒)
@Min(-1)
private Integer refreshTokenTimeToLive = 604800;
@NotNull
private Duration refreshTokenTimeToLive = Duration.ofDays(7);
private boolean allowMultiLogin = true;
// JWT 配置项(type 为 jwt 时必填)
@Valid
private JwtConfig jwt;
// Redis令牌配置项(type 为 redis-token 时使用)
@Valid
private RedisTokenConfig redisToken;
/**
* 校验令牌期限为整秒,且访问期限不超过会话期限
*/
@AssertTrue(message = "令牌有效期须为正整数秒,且访问令牌有效期不能超过刷新令牌有效期")
public boolean isLifetimeValid() {
return accessTokenTimeToLive != null && refreshTokenTimeToLive != null
&& accessTokenTimeToLive.getNano() == 0 && refreshTokenTimeToLive.getNano() == 0
&& accessTokenTimeToLive.toSeconds() > 0 && refreshTokenTimeToLive.toSeconds() > 0
&& accessTokenTimeToLive.compareTo(refreshTokenTimeToLive) <= 0;
}
/**
* 校验所选 JWT 策略的签名密钥长度
*/
@AssertTrue(message = "JWT 模式须配置至少 32 字节的 UTF-8 签名密钥")
public boolean isSigningKeyValid() {
return !"jwt".equals(type) || jwt != null && jwt.secretKey != null
&& jwt.secretKey.getBytes(StandardCharsets.UTF_8).length >= 32;
}
}
/**
* JWT 配置嵌套类
* JWT 签名配置
*/
@Data
public static class JwtConfig {
// JWT签名密钥
@NotNull(message = "JWT 密钥不能为空")
private String secretKey;
}
/**
* Redis令牌配置嵌套类
*/
@Data
public static class RedisTokenConfig {
// 是否允许多设备同时登录
private Boolean allowMultiLogin = true;
}
}
@@ -0,0 +1,26 @@
package com.youlai.boot.framework.security.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Clock;
/**
* 会话基础组件配置
*
* @author Ray.Hao
* @since 4.13.0
*/
@Configuration(proxyBeanMethods = false)
public class SessionConfig {
/**
* 提供认证使用的 UTC 时钟
*/
@Bean
@ConditionalOnMissingBean
public Clock securityClock() {
return Clock.systemUTC();
}
}
@@ -1,67 +0,0 @@
package com.youlai.boot.framework.security.filter;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.framework.security.token.TokenManager;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* Token 认证过滤器。
*
* @author wangtao
* @since 2025/3/6
*/
public class TokenAuthenticationFilter extends OncePerRequestFilter {
private final TokenManager tokenManager;
public TokenAuthenticationFilter(TokenManager tokenManager) {
this.tokenManager = tokenManager;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String rawToken = resolveToken(request);
if (StrUtil.isNotBlank(rawToken)) {
try {
boolean isValid = tokenManager.validateToken(rawToken);
if (!isValid) {
SecurityContextHolder.clearContext();
throw new InsufficientAuthenticationException("Token 无效或已过期");
}
Authentication authentication = tokenManager.parseToken(rawToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (AuthenticationException ex) {
SecurityContextHolder.clearContext();
throw ex;
} catch (Exception ex) {
SecurityContextHolder.clearContext();
throw new InsufficientAuthenticationException("Token 认证失败", ex);
}
}
filterChain.doFilter(request, response);
}
private String resolveToken(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (StrUtil.isNotBlank(header) && header.startsWith(SecurityConstants.BEARER_TOKEN_PREFIX)) {
return header.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length());
}
return null;
}
}
@@ -2,8 +2,8 @@ package com.youlai.boot.framework.security.handler;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.framework.web.util.ResponseWriter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -19,17 +19,17 @@ import java.io.IOException;
* @author Ray.Hao
* @since 2.0.0
*/
@Slf4j
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
if (authException instanceof BadCredentialsException) {
ResponseWriter.writeError(response, ResultCode.USER_PASSWORD_ERROR);
} else if (authException instanceof InsufficientAuthenticationException) {
ResponseWriter.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
if (authException instanceof AuthenticationServiceException) {
log.error("认证服务不可用", authException);
ResponseWriter.writeError(response, ResultCode.AUTH_SERVICE_UNAVAILABLE);
} else {
ResponseWriter.writeError(response, ResultCode.USER_LOGIN_EXCEPTION, authException.getMessage());
ResponseWriter.writeError(response, ResultCode.ACCESS_TOKEN_INVALID);
}
}
}
@@ -1,30 +0,0 @@
package com.youlai.boot.framework.security.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Data;
/**
* 认证令牌响应对象
*
* @author Ray.Hao
* @since 0.0.1
*/
@Schema(description = "认证令牌响应对象")
@Data
@Builder
public class AuthenticationToken {
@Schema(description = "令牌类型", example = "Bearer")
private String tokenType;
@Schema(description = "访问令牌")
private String accessToken;
@Schema(description = "刷新令牌")
private String refreshToken;
@Schema(description = "过期时间(单位:秒)")
private Integer expiresIn;
}
@@ -1,12 +1,13 @@
package com.youlai.boot.framework.security.model;
import lombok.Data;
import lombok.ToString;
import java.util.List;
import java.util.Set;
/**
* 安全模块用户数据 POJO。
* 安全模块用户数据 POJO
*
* @author Ray.Hao
* @since 2025/12/16
@@ -27,6 +28,7 @@ public class SecurityUser {
private Long deptId;
// 密码(加密后)
@ToString.Exclude
private String password;
// 状态(1:启用 其它:禁用)
@@ -5,6 +5,7 @@ import cn.hutool.core.util.ObjectUtil;
import com.youlai.boot.common.constant.SecurityConstants;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@@ -13,10 +14,11 @@ import java.util.*;
import java.util.stream.Collectors;
/**
* Spring Security 用户认证对象。
* Spring Security 用户认证对象
*
* @author Ray.Hao
* @version 3.0.0
* @since 4.13.0
*/
@Data
@NoArgsConstructor
@@ -29,6 +31,7 @@ public class SecurityUserDetails implements UserDetails {
private String username;
// 密码
@ToString.Exclude
private String password;
// 账号是否启用(true:启用 false:禁用)
@@ -44,7 +47,7 @@ public class SecurityUserDetails implements UserDetails {
private Set<String> roles;
/**
* 构造函数:根据 {@link SecurityUser} 初始化。
* 构造函数:根据 {@link SecurityUser} 初始化
*/
public SecurityUserDetails(SecurityUser user) {
this.userId = user.getUserId();
@@ -78,7 +81,7 @@ public class SecurityUserDetails implements UserDetails {
@Override
public boolean isEnabled() {
return this.enabled;
return Boolean.TRUE.equals(this.enabled);
}
/**
@@ -0,0 +1,29 @@
package com.youlai.boot.framework.security.model;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* 登录与刷新共用的令牌响应
*
* @author Ray.Hao
* @since 4.13.0
*/
@Schema(description = "登录令牌")
public record TokenPair(
@Schema(description = "令牌类型", example = "Bearer") String tokenType,
@Schema(description = "访问令牌") String accessToken,
@Schema(description = "刷新令牌") String refreshToken,
@Schema(description = "访问令牌剩余有效期,单位秒") long expiresIn) {
/**
* 创建 Bearer 令牌响应,有效期单位为秒
*/
public static TokenPair bearer(String accessToken, String refreshToken, long expiresIn) {
return new TokenPair("Bearer", accessToken, refreshToken, expiresIn);
}
@Override
public String toString() {
return "TokenPair[tokenType=" + tokenType + ", expiresIn=" + expiresIn + ", credentials=REDACTED]";
}
}
@@ -1,17 +1,24 @@
package com.youlai.boot.framework.security.port;
import com.youlai.boot.common.enums.SocialPlatformEnum;
import com.youlai.boot.framework.security.model.SecurityUser;
/**
* 用户认证信息查询端口。
* 用户认证信息查询端口
*
* @see com.youlai.boot.system.adapter.security.UserAuthenticationAdapter
*
* @author Ray.Hao
* @since 4.13.0
*/
public interface UserAuthenticationPort {
/**
* 根据用户名查询认证信息。
* 根据稳定的用户 ID 重新装载账号状态和权限
*/
SecurityUser getAuthInfoByUserId(Long userId);
/**
* 根据用户名查询认证信息
*
* @param username 用户名
* @return 认证信息,不存在返回 null
@@ -19,7 +26,7 @@ public interface UserAuthenticationPort {
SecurityUser getAuthInfoByUsername(String username);
/**
* 根据手机号查询认证信息。
* 根据手机号查询认证信息
*
* @param mobile 手机号
* @return 认证信息,不存在返回 null
@@ -27,11 +34,11 @@ public interface UserAuthenticationPort {
SecurityUser getAuthInfoByMobile(String mobile);
/**
* 根据第三方平台 openid 查询认证信息。
* 根据具体认证源和来源方账号 ID 查询认证信息
*
* @param platform 第三方平台
* @param openid openid
* @param provider 固定认证源标识,不是协议类型
* @param providerAccountId 来源方账号 ID
* @return 认证信息,未绑定返回 null
*/
SecurityUser getAuthInfoByOpenid(SocialPlatformEnum platform, String openid);
SecurityUser getAuthInfoByProviderAccount(String provider, String providerAccountId);
}
@@ -0,0 +1,27 @@
package com.youlai.boot.framework.security.session;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import java.time.Instant;
/**
* 已验证的会话身份与访问凭证期限
*
* @author Ray.Hao
* @since 4.13.0
*/
public record AuthenticatedSession(String id, SessionPrincipal principal, LoginContext context,
Instant accessExpiresAt) {
/**
* 转换为携带会话详情的 Spring Security 认证结果
*/
public Authentication toAuthentication() {
var details = principal.toUserDetails();
var authentication = UsernamePasswordAuthenticationToken.authenticated(
details, null, details.getAuthorities());
authentication.setDetails(this);
return authentication;
}
}
@@ -0,0 +1,54 @@
package com.youlai.boot.framework.security.session;
import java.util.Objects;
/**
* 登录来源与外部身份,随本地会话保存
*
* @author Ray.Hao
* @since 4.13.0
*/
public record LoginContext(Source source, String provider, String issuer, String subject, String idToken) {
/**
* 登录身份来源
*/
public enum Source {
LOCAL,
OIDC
}
public LoginContext {
Objects.requireNonNull(source, "source");
if (source == Source.OIDC && (provider == null || provider.isBlank()
|| issuer == null || issuer.isBlank() || subject == null || subject.isBlank())) {
throw new IllegalArgumentException("OIDC context requires provider, issuer and subject");
}
if (source == Source.LOCAL && (provider != null || issuer != null || subject != null || idToken != null)) {
throw new IllegalArgumentException("Local context cannot contain an external identity");
}
}
/**
* 创建本地登录上下文
*/
public static LoginContext local() {
return new LoginContext(Source.LOCAL, null, null, null, null);
}
/**
* 保存 OIDC 身份,ID Token 用于认证中心登出
*/
public static LoginContext oidc(String provider, String issuer, String subject, String idToken) {
return new LoginContext(Source.OIDC, provider, issuer, subject, idToken);
}
/**
* 日志不输出 ID Token
*/
@Override
public String toString() {
return "LoginContext[source=" + source + ", provider=" + provider
+ ", issuer=" + issuer + ", subject=" + subject + "]";
}
}
@@ -0,0 +1,11 @@
package com.youlai.boot.framework.security.session;
/**
* Redis 中的会话记录。expiresAt 为固定截止时间,刷新不会延长它
*
* @author Ray.Hao
* @since 4.13.0
*/
public record LoginSession(String id, String generation, SessionPrincipal principal, LoginContext context,
String refreshDigest, long createdAt, long expiresAt) {
}
@@ -0,0 +1,223 @@
package com.youlai.boot.framework.security.session;
import com.youlai.boot.framework.security.token.AccessTokenCodec;
import com.youlai.boot.framework.security.token.SecureTokenGenerator;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
import java.time.Instant;
import java.util.List;
import java.util.function.Supplier;
/**
* 保存会话和凭证摘要,使用原子脚本处理登录与刷新竞争
*
* @author Ray.Hao
* @since 4.13.0
*/
@Component
public class RedisSessionStore {
private static final String PREFIX = "auth:v3:";
private static final long REFRESH_OVERLAP_MILLIS = 5_000;
// 登录发布、单设备替换和不透明令牌索引必须一起完成
private static final DefaultRedisScript<Long> CREATE = new DefaultRedisScript<>("""
local generation = redis.call('GET', KEYS[2])
if generation ~= ARGV[1] or redis.call('EXISTS', KEYS[1]) == 1 then
return 0
end
redis.call('SET', KEYS[2], ARGV[2])
redis.call('SET', KEYS[1], ARGV[3], 'PX', ARGV[4])
if ARGV[5] ~= '' then
redis.call('SET', KEYS[3], ARGV[5], 'PX', ARGV[6])
end
return 1
""", Long.class);
// 刷新轮换:会话代次、刷新凭证与令牌索引一次写入
private static final DefaultRedisScript<Long> ROTATE = new DefaultRedisScript<>("""
local raw = redis.call('GET', KEYS[1])
if not raw then return 0 end
local session = cjson.decode(raw)
local now = tonumber(ARGV[3])
if redis.call('GET', KEYS[2]) ~= session.generation or tonumber(session.expiresAt) <= now then
return 0
end
if session.refreshDigest ~= ARGV[1] then
local consumedAt = redis.call('GET', KEYS[3])
-- 短时间内的并发刷新只拒绝重复请求;较晚的已用凭证重放撤销整条会话
if consumedAt and now - tonumber(consumedAt) > tonumber(ARGV[7]) then
redis.call('DEL', KEYS[1])
end
return 0
end
if ARGV[2] == '' then return 0 end
redis.call('SET', KEYS[3], ARGV[3], 'PX', ARGV[4])
redis.call('SET', KEYS[1], ARGV[2], 'PX', ARGV[4])
if ARGV[5] ~= '' then
redis.call('SET', KEYS[4], ARGV[5], 'PX', ARGV[6])
end
return 1
""", Long.class);
private final StringRedisTemplate redis;
private final JsonMapper json;
public RedisSessionStore(StringRedisTemplate redis, JsonMapper json) {
this.redis = redis;
this.json = json;
}
/**
* 读取用户会话版本,首次访问时生成
*/
public String currentGeneration(Long userId) {
return execute(() -> {
String key = generationKey(userId);
redis.opsForValue().setIfAbsent(key, SecureTokenGenerator.generate());
String generation = redis.opsForValue().get(key);
if (generation == null) {
throw unavailable();
}
return generation;
});
}
/**
* 更换用户会话版本,使既有会话失效
*/
public void revokeUserSessions(Long userId) {
execute(() -> {
redis.opsForValue().set(generationKey(userId), SecureTokenGenerator.generate());
return null;
});
}
/**
* 删除指定会话
*/
public void revokeSession(String sessionId) {
execute(() -> redis.delete(sessionKey(sessionId)));
}
/**
* 原子校验用户版本并保存会话与访问凭证索引
*/
public boolean create(LoginSession session, String expectedGeneration,
AccessTokenCodec.IssuedToken accessToken, Instant now) {
return execute(() -> Long.valueOf(1).equals(redis.execute(CREATE,
List.of(sessionKey(session.id()), generationKey(session.principal().userId()), accessKey(accessToken)),
expectedGeneration, session.generation(), json.writeValueAsString(session),
remaining(session.expiresAt(), now), accessJson(accessToken), accessRemaining(accessToken, now))));
}
/**
* 读取未过期且用户版本仍有效的会话
*/
public LoginSession findActive(String sessionId, Instant now) {
return execute(() -> {
String raw = redis.opsForValue().get(sessionKey(sessionId));
if (raw == null) {
return null;
}
LoginSession session = json.readValue(raw, LoginSession.class);
String generation = redis.opsForValue().get(generationKey(session.principal().userId()));
if (!session.generation().equals(generation) || session.expiresAt() <= now.toEpochMilli()) {
return null;
}
return session;
});
}
/**
* 通过随机访问凭证的摘要查找会话引用
*/
public AccessTokenCodec.Reference findAccessToken(String digest) {
return execute(() -> {
String raw = redis.opsForValue().get(PREFIX + "access:" + digest);
return raw == null ? null : json.readValue(raw, AccessTokenCodec.Reference.class);
});
}
/**
* 原子轮换刷新凭证;替换值为空时仅检查旧凭证重放
*/
public boolean rotate(LoginSession previous, String presentedDigest, LoginSession replacement,
AccessTokenCodec.IssuedToken accessToken, Instant now) {
return execute(() -> Long.valueOf(1).equals(redis.execute(ROTATE,
List.of(sessionKey(previous.id()), generationKey(previous.principal().userId()),
PREFIX + "refresh-used:" + previous.id() + ":" + presentedDigest,
accessToken == null ? sessionKey(previous.id()) : accessKey(accessToken)),
presentedDigest, replacement == null ? "" : json.writeValueAsString(replacement),
Long.toString(now.toEpochMilli()), remaining(previous.expiresAt(), now),
accessToken == null ? "" : accessJson(accessToken),
accessToken == null ? "1" : accessRemaining(accessToken, now),
Long.toString(REFRESH_OVERLAP_MILLIS))));
}
/**
* 序列化随机令牌的会话引用,JWT 不保存该索引
*/
private String accessJson(AccessTokenCodec.IssuedToken token) {
return token.lookupDigest() == null ? "" : json.writeValueAsString(token.reference());
}
/**
* 构造随机令牌索引键,JWT 使用会话键占位
*/
private static String accessKey(AccessTokenCodec.IssuedToken token) {
return token.lookupDigest() == null ? sessionKey(token.reference().sessionId())
: PREFIX + "access:" + token.lookupDigest();
}
/**
* 计算访问凭证剩余有效毫秒数
*/
private static String accessRemaining(AccessTokenCodec.IssuedToken token, Instant now) {
return remaining(token.reference().expiresAt().toEpochMilli(), now);
}
/**
* 计算剩余有效毫秒数,最小值为 1
*/
private static String remaining(long expiresAt, Instant now) {
return Long.toString(Math.max(1, expiresAt - now.toEpochMilli()));
}
/**
* 构造会话存储键
*/
private static String sessionKey(String sessionId) {
return PREFIX + "session:" + sessionId;
}
/**
* 构造用户会话版本键
*/
private static String generationKey(Long userId) {
return PREFIX + "user-generation:" + userId;
}
/**
* 执行存储操作,将存储和解析故障转换为认证服务异常
*/
private static <T> T execute(Supplier<T> operation) {
try {
return operation.get();
} catch (DataAccessException exception) {
throw new AuthenticationServiceException("Session storage is unavailable", exception);
} catch (tools.jackson.core.JacksonException exception) {
throw new AuthenticationServiceException("Session data cannot be read", exception);
}
}
/**
* 创建会话存储不可用异常
*/
private static AuthenticationServiceException unavailable() {
return new AuthenticationServiceException("Session storage is unavailable");
}
}
@@ -0,0 +1,48 @@
package com.youlai.boot.framework.security.session;
import com.youlai.boot.framework.security.model.RoleDataScope;
import com.youlai.boot.framework.security.model.SecurityUser;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import java.util.List;
import java.util.Set;
/**
* 会话中的业务身份,不保存密码
*
* @author Ray.Hao
* @since 4.13.0
*/
public record SessionPrincipal(Long userId, String username, Long deptId,
Set<String> roles, List<RoleDataScope> dataScopes) {
public SessionPrincipal {
roles = roles == null ? Set.of() : Set.copyOf(roles);
dataScopes = dataScopes == null ? List.of() : dataScopes.stream()
.map(scope -> new RoleDataScope(scope.getRoleCode(), scope.getDataScope(),
scope.getCustomDeptIds() == null ? null : List.copyOf(scope.getCustomDeptIds())))
.toList();
}
/**
* 从业务账号提取会话身份与权限范围
*/
public static SessionPrincipal from(SecurityUser user) {
return new SessionPrincipal(user.getUserId(), user.getUsername(), user.getDeptId(),
user.getRoles(), user.getDataScopes());
}
/**
* 转换为不含密码的 Spring Security 用户详情
*/
public SecurityUserDetails toUserDetails() {
var details = new SecurityUserDetails();
details.setUserId(userId);
details.setUsername(username);
details.setDeptId(deptId);
details.setEnabled(true);
details.setRoles(roles);
details.setDataScopes(dataScopes);
return details;
}
}
@@ -0,0 +1,247 @@
package com.youlai.boot.framework.security.session;
import com.youlai.boot.common.exception.TokenInvalidException;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.framework.security.config.SecurityProperties;
import com.youlai.boot.framework.security.model.SecurityUser;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import com.youlai.boot.framework.security.model.TokenPair;
import com.youlai.boot.framework.security.port.UserAuthenticationPort;
import com.youlai.boot.framework.security.token.AccessTokenCodec;
import com.youlai.boot.framework.security.token.SecureTokenGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
/**
* 管理登录会话的创建、校验、刷新与撤销
*
* @author Ray.Hao
* @since 4.13.0
*/
@Service
@RequiredArgsConstructor
public class SessionService {
private final RedisSessionStore store;
private final AccessTokenCodec tokens;
private final SecurityProperties properties;
private final Clock clock;
// 延迟解析业务端口,避免用户管理服务与会话服务形成构造依赖环
private final ObjectProvider<UserAuthenticationPort> users;
private final ObjectProvider<SessionValidator> validators;
/**
* 创建登录会话,并限制其最长有效期
*/
public TokenPair create(Authentication authentication) {
return create(authentication, LoginContext.local());
}
/**
* 创建登录会话,并限制其最长有效期
*/
public TokenPair create(Authentication authentication, LoginContext context) {
if (!authentication.isAuthenticated()
|| !(authentication.getPrincipal() instanceof SecurityUserDetails principal)
|| principal.getUserId() == null) {
throw invalidAccess();
}
Instant now = now();
Instant expiresAt = now.plus(properties.getToken().getRefreshTokenTimeToLive());
if (!expiresAt.isAfter(now)) {
throw invalidAccess();
}
String sessionId = SecureTokenGenerator.generate();
String secret = SecureTokenGenerator.generate();
var access = tokens.issue(sessionId, principal.getUserId(), now, accessExpiry(now, expiresAt));
// 微信注册等事务提交后才发布会话;回滚不会留下可用凭证
afterCommit(() -> publish(sessionId, principal.getUserId(), context, secret, now, expiresAt, access));
return pair(access, sessionId, secret, now);
}
/**
* 校验访问凭证、本地会话与外部登录来源
*/
public AuthenticatedSession authenticate(String accessToken) {
var reference = tokens.verify(accessToken);
Instant now = now();
if (!reference.expiresAt().isAfter(now)) {
throw invalidAccess();
}
LoginSession session = store.findActive(reference.sessionId(), now);
if (session == null || !session.principal().userId().equals(reference.userId())) {
throw invalidAccess();
}
validateSource(session);
return new AuthenticatedSession(session.id(), session.principal(), session.context(), reference.expiresAt());
}
/**
* 每次刷新轮换凭证,并重新装载账号状态及权限
*/
public TokenPair refresh(String refreshToken) {
if (refreshToken == null || !refreshToken.matches("rt\\.[A-Za-z0-9_-]{43}\\.[A-Za-z0-9_-]{43}")) {
throw invalidRefresh();
}
String[] parts = refreshToken.split("\\.");
Instant now = now();
LoginSession previous = store.findActive(parts[1], now);
if (previous == null) {
throw invalidRefresh();
}
String digest = SecureTokenGenerator.digest(parts[2]);
if (!SecureTokenGenerator.matches(previous.refreshDigest(), digest)) {
store.rotate(previous, digest, null, null, now);
throw invalidRefresh();
}
try {
validateSource(previous);
SessionPrincipal principal = loadPrincipal(previous.principal().userId());
String secret = SecureTokenGenerator.generate();
var replacement = new LoginSession(previous.id(), previous.generation(), principal, previous.context(),
SecureTokenGenerator.digest(secret), previous.createdAt(), previous.expiresAt());
var access = tokens.issue(previous.id(), principal.userId(), now,
accessExpiry(now, Instant.ofEpochMilli(previous.expiresAt())));
if (!store.rotate(previous, digest, replacement, access, now)) {
throw invalidRefresh();
}
return pair(access, previous.id(), secret, now);
} catch (BadCredentialsException exception) {
store.revokeSession(previous.id());
throw invalidRefresh();
}
}
/**
* 撤销指定登录会话
*/
public void revokeSession(String sessionId) {
store.revokeSession(sessionId);
}
/**
* 数据库事务提交成功后撤销,避免回滚操作误踢用户
*/
public void revokeUserSessions(Long userId) {
afterCommit(() -> store.revokeUserSessions(userId));
}
/**
* 检查用户版本并发布会话,竞争失败时有限重试
*/
private void publish(String sessionId, Long userId, LoginContext context, String secret,
Instant createdAt, Instant expiresAt, AccessTokenCodec.IssuedToken access) {
for (int attempt = 0; attempt < 3; attempt++) {
String expectedGeneration = store.currentGeneration(userId);
String generation = properties.getToken().isAllowMultiLogin()
? expectedGeneration : SecureTokenGenerator.generate();
var session = new LoginSession(sessionId, generation, loadPrincipal(userId), context,
SecureTokenGenerator.digest(secret), createdAt.toEpochMilli(), expiresAt.toEpochMilli());
validateSource(session);
Instant now = now();
if (!access.reference().expiresAt().isAfter(now)) {
throw invalidAccess();
}
if (store.create(session, expectedGeneration, access, now)) {
return;
}
}
throw new BadCredentialsException("Account state changed during login; retry login");
}
/**
* 重新加载有效账号及其权限
*/
private SessionPrincipal loadPrincipal(Long userId) {
SecurityUser user;
try {
user = users.getObject().getAuthInfoByUserId(userId);
} catch (DataAccessException exception) {
throw new AuthenticationServiceException("Account storage is unavailable", exception);
}
if (user == null || !userId.equals(user.getUserId()) || !Integer.valueOf(1).equals(user.getStatus())) {
throw invalidAccess();
}
return SessionPrincipal.from(user);
}
/**
* 校验外部登录来源;对应模块关闭时拒绝认证
*/
private void validateSource(LoginSession session) {
if (session.context().source() == LoginContext.Source.LOCAL) {
return;
}
var validator = validators.orderedStream()
.filter(candidate -> candidate.source() == session.context().source())
.findFirst().orElseThrow(SessionService::invalidAccess);
validator.validate(session);
}
/**
* 计算不超过会话期限的访问凭证截止时间
*/
private Instant accessExpiry(Instant now, Instant sessionExpiry) {
Instant accessExpiry = now.plus(properties.getToken().getAccessTokenTimeToLive());
return accessExpiry.isBefore(sessionExpiry) ? accessExpiry : sessionExpiry;
}
/**
* 组合访问令牌、刷新凭证与剩余有效秒数
*/
private static TokenPair pair(AccessTokenCodec.IssuedToken access, String sessionId, String secret, Instant now) {
return TokenPair.bearer(access.value(), "rt." + sessionId + "." + secret,
Duration.between(now, access.reference().expiresAt()).toSeconds());
}
/**
* 获取精确到秒的认证时间
*/
private Instant now() {
return clock.instant().truncatedTo(ChronoUnit.SECONDS);
}
/**
* 事务提交后执行操作,无事务时立即执行
*/
private static void afterCommit(Runnable operation) {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
operation.run();
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
operation.run();
}
});
}
/**
* 创建会话无效异常
*/
private static BadCredentialsException invalidAccess() {
return new BadCredentialsException("Invalid session");
}
/**
* 创建刷新凭证无效异常
*/
private static TokenInvalidException invalidRefresh() {
return new TokenInvalidException(ResultCode.REFRESH_TOKEN_INVALID);
}
}
@@ -0,0 +1,20 @@
package com.youlai.boot.framework.security.session;
/**
* 外部登录来源的会话校验
*
* @author Ray.Hao
* @since 4.13.0
*/
public interface SessionValidator {
/**
* 本校验器负责的登录来源
*/
LoginContext.Source source();
/**
* 校验本实现负责的外部登录来源,失效时拒绝认证
*/
void validate(LoginSession session);
}
@@ -0,0 +1,38 @@
package com.youlai.boot.framework.security.token;
import java.time.Instant;
/**
* 访问令牌格式策略;会话生命周期由 SessionService 管理
*
* @author Ray.Hao
* @since 4.13.0
*/
public interface AccessTokenCodec {
/**
* 签发引用指定会话的访问凭证
*/
IssuedToken issue(String sessionId, Long userId, Instant issuedAt, Instant expiresAt);
/**
* 校验签名或凭证索引,返回引用;账号与会话状态仍须由 SessionService 校验
*/
Reference verify(String token);
/**
* 访问凭证对应的会话、用户与截止时间
*/
record Reference(String sessionId, Long userId, Instant expiresAt) {
}
/**
* lookupDigest 仅用于不透明令牌的 Redis 索引
*/
record IssuedToken(String value, Reference reference, String lookupDigest) {
@Override
public String toString() {
return "IssuedToken[reference=" + reference + ", value=REDACTED]";
}
}
}
@@ -0,0 +1,96 @@
package com.youlai.boot.framework.security.token;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.youlai.boot.framework.security.config.SecurityProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.stereotype.Component;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
/**
* JWT 只携带会话引用,角色和登录来源以服务端会话为准
*
* @author Ray.Hao
* @since 4.13.0
*/
@Component
@ConditionalOnProperty(prefix = "security.token", name = "type", havingValue = "jwt", matchIfMissing = true)
public class JwtAccessTokenCodec implements AccessTokenCodec {
private static final String ISSUER = "youlai-boot";
private static final String AUDIENCE = "youlai-api";
private final JwtEncoder encoder;
private final JwtDecoder decoder;
public JwtAccessTokenCodec(SecurityProperties properties, Clock clock) {
var secret = new SecretKeySpec(properties.getToken().getJwt().getSecretKey()
.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
encoder = new NimbusJwtEncoder(new ImmutableSecret<>(secret));
var nimbus = NimbusJwtDecoder.withSecretKey(secret).macAlgorithm(MacAlgorithm.HS256)
.validateType(false).build();
var timestamp = new JwtTimestampValidator(Duration.ZERO);
timestamp.setClock(clock);
nimbus.setJwtValidator(new DelegatingOAuth2TokenValidator<>(timestamp,
new JwtIssuerValidator(ISSUER), new JwtClaimValidator<List<String>>("aud",
audiences -> audiences != null && audiences.contains(AUDIENCE))));
decoder = nimbus;
}
@Override
public IssuedToken issue(String sessionId, Long userId, Instant issuedAt, Instant expiresAt) {
var claims = JwtClaimsSet.builder().issuer(ISSUER).audience(List.of(AUDIENCE))
.subject(userId.toString()).id(SecureTokenGenerator.generate())
.issuedAt(issuedAt).expiresAt(expiresAt)
.claim("sid", sessionId).claim("token_use", "access").build();
var header = JwsHeader.with(MacAlgorithm.HS256).type("at+jwt").build();
String value = encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
return new IssuedToken(value, new Reference(sessionId, userId, expiresAt), null);
}
@Override
public Reference verify(String token) {
if (token == null || token.length() > 4096) {
throw invalid();
}
try {
Jwt jwt = decoder.decode(token);
String sessionId = jwt.getClaimAsString("sid");
if (!"at+jwt".equals(jwt.getHeaders().get("typ"))
|| !"access".equals(jwt.getClaimAsString("token_use"))
|| sessionId == null || !sessionId.matches("[A-Za-z0-9_-]{43}")
|| jwt.getExpiresAt() == null || jwt.getIssuedAt() == null) {
throw invalid();
}
return new Reference(sessionId, Long.valueOf(jwt.getSubject()), jwt.getExpiresAt());
} catch (JwtException | IllegalArgumentException exception) {
throw invalid();
}
}
/**
* 创建 JWT 凭证无效异常
*/
private static BadCredentialsException invalid() {
return new BadCredentialsException("Invalid access token");
}
}
@@ -1,299 +0,0 @@
package com.youlai.boot.framework.security.token;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.youlai.boot.common.constant.JwtClaimConstants;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.framework.security.config.SecurityProperties;
import com.youlai.boot.common.exception.TokenInvalidException;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.RoleDataScope;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* JWT Token 管理器。
*
* @author Ray.Hao
* @since 2024/11/15
*/
@ConditionalOnProperty(value = "security.token.type", havingValue = "jwt")
@Service
public class JwtTokenManager implements TokenManager {
// 允许的签名算法,防止 alg:none 等算法降级攻击
private static final String ALLOWED_ALGORITHM = "HS256";
private final SecurityProperties securityProperties;
private final RedisTemplate<String, Object> redisTemplate;
private final byte[] secretKey;
public JwtTokenManager(SecurityProperties securityProperties, RedisTemplate<String, Object> redisTemplate) {
this.securityProperties = securityProperties;
this.redisTemplate = redisTemplate;
this.secretKey = securityProperties.getToken().getJwt().getSecretKey().getBytes();
}
@Override
public AuthenticationToken generateToken(Authentication authentication) {
int accessTokenTimeToLive = securityProperties.getToken().getAccessTokenTimeToLive();
int refreshTokenTimeToLive = securityProperties.getToken().getRefreshTokenTimeToLive();
String accessToken = generateToken(authentication, accessTokenTimeToLive);
String refreshToken = generateToken(authentication, refreshTokenTimeToLive, true);
return AuthenticationToken.builder()
.accessToken(accessToken)
.refreshToken(refreshToken)
.tokenType("Bearer")
.expiresIn(accessTokenTimeToLive)
.build();
}
@Override
public Authentication parseToken(String token) {
JWT jwt = JWTUtil.parseToken(token);
if (!isAlgorithmAllowed(jwt) || !jwt.setKey(secretKey).verify()) {
throw new TokenInvalidException(ResultCode.ACCESS_TOKEN_INVALID);
}
JSONObject payloads = jwt.getPayloads();
SecurityUserDetails userDetails = new SecurityUserDetails();
userDetails.setUserId(payloads.getLong(JwtClaimConstants.USER_ID));
userDetails.setDeptId(payloads.getLong(JwtClaimConstants.DEPT_ID));
// 数据权限
JSONArray dataScopesArray = payloads.getJSONArray(JwtClaimConstants.DATA_SCOPES);
if (dataScopesArray != null && !dataScopesArray.isEmpty()) {
List<RoleDataScope> dataScopes = dataScopesArray.stream()
.map(obj -> {
JSONObject item = (JSONObject) obj;
String roleCode = item.getStr("roleCode");
Integer dataScope = item.getInt("dataScope");
JSONArray deptIdsArray = item.getJSONArray("customDeptIds");
List<Long> customDeptIds = null;
if (deptIdsArray != null) {
customDeptIds = deptIdsArray.toList(Long.class);
}
return new RoleDataScope(roleCode, dataScope, customDeptIds);
})
.collect(Collectors.toList());
userDetails.setDataScopes(dataScopes);
}
userDetails.setUsername(payloads.getStr(JWTPayload.SUBJECT));
// 角色编码(不带 ROLE_ 前缀)
JSONArray rolesArray = payloads.getJSONArray(JwtClaimConstants.ROLES);
if (rolesArray != null && !rolesArray.isEmpty()) {
Set<String> roles = rolesArray.stream()
.map(Convert::toStr)
.collect(Collectors.toSet());
userDetails.setRoles(roles);
}
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}
@Override
public boolean validateToken(String token) {
return validateToken(token, false);
}
@Override
public boolean validateRefreshToken(String refreshToken) {
return validateToken(refreshToken, true);
}
private boolean validateToken(String token, boolean validateRefreshToken) {
JWT jwt = JWTUtil.parseToken(token);
if (!isAlgorithmAllowed(jwt)) {
return false;
}
boolean isValid = jwt.setKey(secretKey).validate(0);
if (isValid) {
JSONObject payloads = jwt.getPayloads();
// 刷新令牌类型校验
String jti = payloads.getStr(JWTPayload.JWT_ID);
if (validateRefreshToken) {
boolean isRefreshToken = payloads.getBool(JwtClaimConstants.TOKEN_TYPE);
if (!isRefreshToken) {
return false;
}
}
// tokenVersion 校验(用户维度 Token 失效)
Long userId = payloads.getLong(JwtClaimConstants.USER_ID);
if (userId != null) {
Integer tokenVersion = payloads.getInt(JwtClaimConstants.TOKEN_VERSION);
String versionKey = StrUtil.format(RedisConstants.Auth.USER_TOKEN_VERSION, userId);
Object currentVersionObj = redisTemplate.opsForValue().get(versionKey);
int currentVersion = currentVersionObj != null ? Convert.toInt(currentVersionObj) : 0;
if (tokenVersion == null || tokenVersion < currentVersion) {
return false;
}
}
// jti 黑名单校验
if (isTokenRevoked(jti)) {
return false;
}
}
return isValid;
}
@Override
public void invalidateToken(String token) {
if (StringUtils.isBlank(token)) {
return;
}
if (token.startsWith(SecurityConstants.BEARER_TOKEN_PREFIX)) {
token = token.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length());
}
JWT jwt = JWTUtil.parseToken(token);
if (!isAlgorithmAllowed(jwt) || !jwt.setKey(secretKey).verify()) {
return;
}
JSONObject payloads = jwt.getPayloads();
String jti = payloads.getStr(JWTPayload.JWT_ID);
Integer expirationAt = payloads.getInt(JWTPayload.EXPIRES_AT);
revokeTokenByJti(jti, expirationAt);
}
@Override
public void invalidateUserSessions(Long userId) {
if (userId == null) {
return;
}
String versionKey = StrUtil.format(RedisConstants.Auth.USER_TOKEN_VERSION, userId);
redisTemplate.opsForValue().increment(versionKey);
}
@Override
public AuthenticationToken refreshToken(String refreshToken) {
boolean isValid = validateRefreshToken(refreshToken);
if (!isValid) {
throw new TokenInvalidException(ResultCode.REFRESH_TOKEN_INVALID);
}
Authentication authentication = parseToken(refreshToken);
int accessTokenExpiration = securityProperties.getToken().getAccessTokenTimeToLive();
String newAccessToken = generateToken(authentication, accessTokenExpiration);
return AuthenticationToken.builder()
.accessToken(newAccessToken)
.refreshToken(refreshToken)
.tokenType("Bearer")
.expiresIn(accessTokenExpiration)
.build();
}
// ======================== private ========================
private String generateToken(Authentication authentication, int ttl) {
return generateToken(authentication, ttl, false);
}
private String generateToken(Authentication authentication, int ttl, boolean isRefreshToken) {
SecurityUserDetails userDetails = (SecurityUserDetails) authentication.getPrincipal();
Map<String, Object> payload = new HashMap<>();
payload.put(JwtClaimConstants.USER_ID, userDetails.getUserId());
payload.put(JwtClaimConstants.DEPT_ID, userDetails.getDeptId());
// 数据权限
List<RoleDataScope> dataScopes = userDetails.getDataScopes();
if (dataScopes != null && !dataScopes.isEmpty()) {
List<Map<String, Object>> scopesList = dataScopes.stream()
.map(scope -> {
Map<String, Object> scopeMap = new HashMap<>();
scopeMap.put("roleCode", scope.getRoleCode());
scopeMap.put("dataScope", scope.getDataScope());
scopeMap.put("customDeptIds", scope.getCustomDeptIds());
return scopeMap;
})
.collect(Collectors.toList());
payload.put(JwtClaimConstants.DATA_SCOPES, scopesList);
}
// 角色编码(不带 ROLE_ 前缀)
Set<String> roles = userDetails.getRoles();
if (roles != null && !roles.isEmpty()) {
payload.put(JwtClaimConstants.ROLES, roles);
}
Long userId = userDetails.getUserId();
int tokenVersion = 0;
if (userId != null) {
String versionKey = StrUtil.format(RedisConstants.Auth.USER_TOKEN_VERSION, userId);
Object versionObj = redisTemplate.opsForValue().get(versionKey);
tokenVersion = versionObj != null ? Convert.toInt(versionObj) : 0;
}
payload.put(JwtClaimConstants.TOKEN_VERSION, tokenVersion);
Date now = new Date();
payload.put(JWTPayload.ISSUED_AT, now);
payload.put(JwtClaimConstants.TOKEN_TYPE, isRefreshToken);
if (ttl != -1) {
Date expiresAt = DateUtil.offsetSecond(now, ttl);
payload.put(JWTPayload.EXPIRES_AT, expiresAt);
}
payload.put(JWTPayload.SUBJECT, authentication.getName());
payload.put(JWTPayload.JWT_ID, IdUtil.simpleUUID());
return JWTUtil.createToken(payload, secretKey);
}
private boolean isTokenRevoked(String jti) {
if (StringUtils.isBlank(jti)) {
return false;
}
return Boolean.TRUE.equals(redisTemplate.hasKey(StrUtil.format(RedisConstants.Auth.REVOKED_JTI, jti)));
}
private void revokeTokenByJti(String jti, Integer expirationAt) {
if (StringUtils.isBlank(jti)) {
return;
}
String revokedJtiKey = StrUtil.format(RedisConstants.Auth.REVOKED_JTI, jti);
if (expirationAt != null) {
int currentTimeSeconds = Convert.toInt(System.currentTimeMillis() / 1000);
if (expirationAt < currentTimeSeconds) {
return;
}
int expirationIn = expirationAt - currentTimeSeconds;
redisTemplate.opsForValue().set(revokedJtiKey, Boolean.TRUE, expirationIn, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(revokedJtiKey, Boolean.TRUE);
}
}
/**
* 校验 JWT 头部算法是否在允许的白名单中,防止 alg:none 等算法降级攻击
*
* @param jwt JWT 对象
* @return 是否允许
*/
private boolean isAlgorithmAllowed(JWT jwt) {
Object algorithm = jwt.getHeader("alg");
return algorithm != null && ALLOWED_ALGORITHM.equals(algorithm.toString());
}
}
@@ -0,0 +1,48 @@
package com.youlai.boot.framework.security.token;
import com.youlai.boot.framework.security.session.RedisSessionStore;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
import java.time.Instant;
/**
* Redis Token 是随机凭证,服务端通过摘要查找会话引用
*
* @author Ray.Hao
* @since 4.13.0
*/
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "security.token", name = "type", havingValue = "redis-token")
public class OpaqueAccessTokenCodec implements AccessTokenCodec {
private final RedisSessionStore sessions;
@Override
public IssuedToken issue(String sessionId, Long userId, Instant issuedAt, Instant expiresAt) {
String token = SecureTokenGenerator.generate();
return new IssuedToken(token, new Reference(sessionId, userId, expiresAt), SecureTokenGenerator.digest(token));
}
@Override
public Reference verify(String token) {
if (token == null || !token.matches("[A-Za-z0-9_-]{43}")) {
throw invalid();
}
Reference reference = sessions.findAccessToken(SecureTokenGenerator.digest(token));
if (reference == null) {
throw invalid();
}
return reference;
}
/**
* 创建随机访问凭证无效异常
*/
private static BadCredentialsException invalid() {
return new BadCredentialsException("Invalid access token");
}
}
@@ -1,199 +0,0 @@
package com.youlai.boot.framework.security.token;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.youlai.boot.common.constant.RedisConstants;
import com.youlai.boot.common.constant.SecurityConstants;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.framework.security.config.SecurityProperties;
import com.youlai.boot.common.exception.TokenInvalidException;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import tools.jackson.databind.json.JsonMapper;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
/**
* Redis Token 管理器。
*
* @author Ray.Hao
* @since 2024/11/15
*/
@ConditionalOnProperty(value = "security.token.type", havingValue = "redis-token")
@Service
public class RedisTokenManager implements TokenManager {
private final SecurityProperties securityProperties;
private final RedisTemplate<String, Object> redisTemplate;
private final JsonMapper jsonMapper;
public RedisTokenManager(SecurityProperties securityProperties,
RedisTemplate<String, Object> redisTemplate,
JsonMapper jsonMapper) {
this.securityProperties = securityProperties;
this.redisTemplate = redisTemplate;
this.jsonMapper = jsonMapper;
}
@Override
public AuthenticationToken generateToken(Authentication authentication) {
SecurityUserDetails user = (SecurityUserDetails) authentication.getPrincipal();
String accessToken = IdUtil.fastSimpleUUID();
String refreshToken = IdUtil.fastSimpleUUID();
// 构建会话快照(不存密码)
SecurityUserDetails sessionUser = buildSessionUser(user);
storeTokensInRedis(accessToken, refreshToken, sessionUser);
handleSingleDeviceLogin(user.getUserId(), accessToken);
return AuthenticationToken.builder()
.accessToken(accessToken)
.refreshToken(refreshToken)
.expiresIn(securityProperties.getToken().getAccessTokenTimeToLive())
.build();
}
@Override
public Authentication parseToken(String token) {
Object raw = redisTemplate.opsForValue().get(formatTokenKey(token));
if (raw == null) return null;
SecurityUserDetails userDetails = jsonMapper.convertValue(raw, SecurityUserDetails.class);
return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
}
@Override
public boolean validateToken(String token) {
return redisTemplate.hasKey(formatTokenKey(token));
}
@Override
public boolean validateRefreshToken(String refreshToken) {
return redisTemplate.hasKey(formatRefreshTokenKey(refreshToken));
}
@Override
public AuthenticationToken refreshToken(String refreshToken) {
Object raw = redisTemplate.opsForValue()
.get(StrUtil.format(RedisConstants.Auth.REFRESH_TOKEN_USER, refreshToken));
if (raw == null) {
throw new TokenInvalidException(ResultCode.REFRESH_TOKEN_INVALID);
}
SecurityUserDetails sessionUser = jsonMapper.convertValue(raw, SecurityUserDetails.class);
Object oldAccessTokenValue = redisTemplate.opsForValue()
.get(StrUtil.format(RedisConstants.Auth.USER_ACCESS_TOKEN, sessionUser.getUserId()));
Optional.of(oldAccessTokenValue)
.map(String.class::cast)
.ifPresent(oldAccessToken -> redisTemplate.delete(formatTokenKey(oldAccessToken)));
String newAccessToken = IdUtil.fastSimpleUUID();
storeAccessToken(newAccessToken, sessionUser);
int accessTtl = securityProperties.getToken().getAccessTokenTimeToLive();
return AuthenticationToken.builder()
.accessToken(newAccessToken)
.refreshToken(refreshToken)
.expiresIn(accessTtl)
.build();
}
@Override
public void invalidateToken(String token) {
String cleanToken = cleanBearerPrefix(token);
redisTemplate.delete(formatTokenKey(cleanToken));
}
@Override
public void invalidateUserSessions(Long userId) {
if (userId == null) {
return;
}
String userAccessKey = StrUtil.format(RedisConstants.Auth.USER_ACCESS_TOKEN, userId);
Object accessTokenValue = redisTemplate.opsForValue().get(userAccessKey);
if (accessTokenValue instanceof String accessToken) {
redisTemplate.delete(formatTokenKey(accessToken));
}
redisTemplate.delete(userAccessKey);
String userRefreshKey = StrUtil.format(RedisConstants.Auth.USER_REFRESH_TOKEN, userId);
Object refreshTokenValue = redisTemplate.opsForValue().get(userRefreshKey);
if (refreshTokenValue instanceof String refreshToken) {
redisTemplate.delete(StrUtil.format(RedisConstants.Auth.REFRESH_TOKEN_USER, refreshToken));
}
redisTemplate.delete(userRefreshKey);
}
// ======================== private ========================
private SecurityUserDetails buildSessionUser(SecurityUserDetails user) {
SecurityUserDetails sessionUser = new SecurityUserDetails();
sessionUser.setUserId(user.getUserId());
sessionUser.setUsername(user.getUsername());
sessionUser.setDeptId(user.getDeptId());
sessionUser.setDataScopes(user.getDataScopes());
sessionUser.setRoles(user.getRoles());
sessionUser.setEnabled(user.isEnabled());
sessionUser.setPassword(null);
return sessionUser;
}
private void storeTokensInRedis(String accessToken, String refreshToken, SecurityUserDetails sessionUser) {
setRedisValue(formatTokenKey(accessToken), sessionUser,
securityProperties.getToken().getAccessTokenTimeToLive());
String refreshTokenKey = StrUtil.format(RedisConstants.Auth.REFRESH_TOKEN_USER, refreshToken);
setRedisValue(refreshTokenKey, sessionUser,
securityProperties.getToken().getRefreshTokenTimeToLive());
setRedisValue(StrUtil.format(RedisConstants.Auth.USER_REFRESH_TOKEN, sessionUser.getUserId()),
refreshToken, securityProperties.getToken().getRefreshTokenTimeToLive());
}
private void handleSingleDeviceLogin(Long userId, String accessToken) {
Boolean allowMultiLogin = securityProperties.getToken().getRedisToken().getAllowMultiLogin();
String userAccessKey = StrUtil.format(RedisConstants.Auth.USER_ACCESS_TOKEN, userId);
if (!allowMultiLogin) {
Object oldAccessTokenValue = redisTemplate.opsForValue().get(userAccessKey);
if (oldAccessTokenValue instanceof String oldAccessToken) {
redisTemplate.delete(formatTokenKey(oldAccessToken));
}
}
setRedisValue(userAccessKey, accessToken, securityProperties.getToken().getAccessTokenTimeToLive());
}
private void storeAccessToken(String newAccessToken, SecurityUserDetails sessionUser) {
setRedisValue(StrUtil.format(RedisConstants.Auth.ACCESS_TOKEN_USER, newAccessToken), sessionUser,
securityProperties.getToken().getAccessTokenTimeToLive());
String userAccessKey = StrUtil.format(RedisConstants.Auth.USER_ACCESS_TOKEN, sessionUser.getUserId());
setRedisValue(userAccessKey, newAccessToken, securityProperties.getToken().getAccessTokenTimeToLive());
}
private String formatTokenKey(String token) {
return StrUtil.format(RedisConstants.Auth.ACCESS_TOKEN_USER, token);
}
private String formatRefreshTokenKey(String refreshToken) {
return StrUtil.format(RedisConstants.Auth.REFRESH_TOKEN_USER, refreshToken);
}
private void setRedisValue(String key, Object value, int ttl) {
if (ttl != -1) {
redisTemplate.opsForValue().set(key, value, ttl, TimeUnit.SECONDS);
} else {
redisTemplate.opsForValue().set(key, value);
}
}
private String cleanBearerPrefix(String token) {
if (token.startsWith(SecurityConstants.BEARER_TOKEN_PREFIX)) {
return token.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length()).trim();
}
return token.trim();
}
}
@@ -0,0 +1,51 @@
package com.youlai.boot.framework.security.token;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
/**
* 生成密码学随机凭证及其 SHA-256 摘要
*
* @author Ray.Hao
* @since 4.13.0
*/
public final class SecureTokenGenerator {
private static final SecureRandom RANDOM = new SecureRandom();
private SecureTokenGenerator() {
}
/**
* 生成 32 字节随机值,并编码为无填充的 Base64URL
*/
public static String generate() {
byte[] bytes = new byte[32];
RANDOM.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
/**
* 计算凭证的 SHA-256 十六进制摘要
*/
public static String digest(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is unavailable", exception);
}
}
/**
* 以恒定时间比较凭证摘要
*/
public static boolean matches(String expected, String actual) {
return MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII),
actual.getBytes(StandardCharsets.US_ASCII));
}
}
@@ -1,72 +0,0 @@
package com.youlai.boot.framework.security.token;
import com.youlai.boot.framework.security.model.AuthenticationToken;
import org.springframework.security.core.Authentication;
/**
* Token 管理器
*
* @author Ray.Hao
* @since 2.16.0
*/
public interface TokenManager {
/**
* 生成认证 Token
*
* @param authentication 用户认证信息
* @return 认证 Token 响应
*/
AuthenticationToken generateToken(Authentication authentication);
/**
* 解析 Token 获取认证信息
*
* @param token Token
* @return 用户认证信息
*/
Authentication parseToken(String token);
/**
* 校验 Token 是否有效
*
* @param token JWT Token
* @return 是否有效
*/
boolean validateToken(String token);
/**
* 校验 刷新 Token 是否有效
*
* @param refreshToken JWT Token
* @return 是否有效
*/
boolean validateRefreshToken(String refreshToken);
/**
* 刷新 Token
*
* @param token 刷新令牌
* @return 认证 Token 响应
*/
AuthenticationToken refreshToken(String token);
/**
* 令 Token 失效
*
* @param token Token
*/
default void invalidateToken(String token) {
}
/**
* 使指定用户的所有会话失效
*
* @param userId 用户ID
*/
default void invalidateUserSessions(Long userId) {
// 默认空实现,由具体 TokenManager 决定是否支持按用户下线
}
}
@@ -3,12 +3,8 @@ package com.youlai.boot.framework.security.util;
import com.youlai.boot.common.constant.SystemConstants;
import com.youlai.boot.framework.security.model.RoleDataScope;
import com.youlai.boot.framework.security.model.SecurityUserDetails;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.*;
@@ -63,7 +59,7 @@ public class SecurityUtils {
}
/**
* 获取角色编码集合,不带 ROLE_ 前缀。
* 获取角色编码集合,不带 ROLE_ 前缀
*/
public static Set<String> getRoles() {
return getUser().map(SecurityUserDetails::getRoles).orElse(Set.of());
@@ -76,16 +72,4 @@ public class SecurityUtils {
return getRoles().contains(SystemConstants.ROOT_ROLE_CODE);
}
/**
* 从请求头获取 Token
*/
public static String getAccessToken() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return null;
}
HttpServletRequest request = attributes.getRequest();
return request.getHeader(HttpHeaders.AUTHORIZATION);
}
}
@@ -7,18 +7,21 @@ import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.common.exception.TokenInvalidException;
import com.youlai.boot.common.exception.RateLimitException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
@@ -26,6 +29,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.servlet.NoHandlerFoundException;
import tools.jackson.core.JacksonException;
@@ -46,29 +50,43 @@ import java.util.stream.Collectors;
public class GlobalExceptionHandler {
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(BindException e) {
log.error("BindException:{}", e.getMessage());
String msg = e.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
return Result.failed(ResultCode.USER_REQUEST_PARAMETER_ERROR, msg);
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(ConstraintViolationException e) {
log.error("ConstraintViolationException:{}", e.getMessage());
String msg = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
return Result.failed(ResultCode.INVALID_USER_INPUT, msg);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(MethodArgumentNotValidException e) {
log.error("MethodArgumentNotValidException:{}", e.getMessage());
String msg = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
return Result.failed(ResultCode.INVALID_USER_INPUT, msg);
}
/**
* 参数约束失败返回400,返回值约束失败保留500
*/
@ExceptionHandler(HandlerMethodValidationException.class)
public ResponseEntity<Result<Void>> handleMethodValidationException(HandlerMethodValidationException e) {
if (e.isForReturnValue()) {
log.error("接口返回值校验失败", e);
return ResponseEntity.status(e.getStatusCode()).body(Result.failed(ResultCode.SYSTEM_ERROR));
}
String message = e.getAllErrors().stream()
.map(MessageSourceResolvable::getDefaultMessage)
.filter(StrUtil::isNotBlank)
.distinct()
.collect(Collectors.joining(";"));
return ResponseEntity.status(e.getStatusCode()).body(Result.failed(ResultCode.INVALID_USER_INPUT, message));
}
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public <T> Result<T> processException(NoHandlerFoundException e) {
@@ -77,14 +95,14 @@ public class GlobalExceptionHandler {
}
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(MissingServletRequestParameterException e) {
log.error(e.getMessage(), e);
return Result.failed(ResultCode.REQUEST_REQUIRED_PARAMETER_IS_EMPTY);
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(MethodArgumentTypeMismatchException e) {
log.error(e.getMessage(), e);
return Result.failed(ResultCode.PARAMETER_FORMAT_MISMATCH, "类型错误");
@@ -98,23 +116,21 @@ public class GlobalExceptionHandler {
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> handleIllegalArgumentException(IllegalArgumentException e) {
log.error("非法参数异常,异常原因:{}", e.getMessage(), e);
return Result.failed(e.getMessage());
}
@ExceptionHandler(JacksonException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> handleJacksonException(JacksonException e) {
log.error("Json转换异常,异常原因:{}", e.getMessage(), e);
return Result.failed(e.getMessage());
return Result.failed(ResultCode.PARAMETER_FORMAT_MISMATCH);
}
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(HttpMessageNotReadableException e) {
log.error(e.getMessage(), e);
String errorMessage = "请求体不可为空";
Throwable cause = e.getCause();
if (cause != null) {
@@ -124,7 +140,7 @@ public class GlobalExceptionHandler {
}
@ExceptionHandler(TypeMismatchException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public <T> Result<T> processException(TypeMismatchException e) {
log.error(e.getMessage(), e);
return Result.failed(e.getMessage());
@@ -160,6 +176,23 @@ public class GlobalExceptionHandler {
return Result.failed(e.getResultCode());
}
@ExceptionHandler(AuthenticationServiceException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public Result<Void> handleAuthenticationServiceException(
AuthenticationServiceException exception) {
log.error("认证服务不可用", exception);
return Result.failed(ResultCode.AUTH_SERVICE_UNAVAILABLE);
}
@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Result<Void> handleAuthenticationException(AuthenticationException exception) {
ResultCode code = exception instanceof DisabledException ? ResultCode.ACCOUNT_FROZEN
: exception instanceof BadCredentialsException ? ResultCode.USER_PASSWORD_ERROR
: ResultCode.USER_LOGIN_EXCEPTION;
return Result.failed(code);
}
@ExceptionHandler(RateLimitException.class)
@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public <T> Result<T> handleRateLimitException(RateLimitException e) {
@@ -178,17 +211,12 @@ public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public <T> Result<T> handleException(Exception e, HttpServletRequest request) throws Exception {
if (e instanceof AccessDeniedException
|| e instanceof AuthenticationException) {
throw e;
}
String accept = request.getHeader("Accept");
if (accept != null && accept.contains(MediaType.TEXT_EVENT_STREAM_VALUE)) {
public <T> Result<T> handleException(Exception e) throws Exception {
if (e instanceof AccessDeniedException) {
throw e;
}
log.error("unknown exception", e);
return Result.failed(e.getLocalizedMessage());
return Result.failed(ResultCode.SYSTEM_ERROR);
}
private String convertMessage(Throwable throwable) {
@@ -0,0 +1,24 @@
package com.youlai.boot.framework.web.advice;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
/**
* 保留重复排序参数中的字段与方向
*
* @author Ray.Hao
* @since 4.13.0
*/
@ControllerAdvice
public class QueryBindingAdvice {
/**
* 将每个 sort 参数作为完整规则,避免按逗号拆成两个数组元素
*/
@InitBinder
public void bindSort(WebDataBinder binder) {
binder.registerCustomEditor(String[].class, "sort", new StringArrayPropertyEditor(null));
}
}
@@ -66,6 +66,11 @@ public class OperationLogAspect {
} finally {
long elapsed = System.currentTimeMillis() - start;
try {
// 登录前没有操作者;退出前已取快照,不能在清理上下文后重新读取
if (logAnnotation.value() == ActionTypeEnum.LOGIN && failure == null) {
userId = SecurityUtils.getUserId();
username = SecurityUtils.getUsername();
}
OperationLog operationLog = buildOperationLog(logAnnotation, elapsed, failure, userId, username);
if (operationLog != null) {
operationLogExecutor.execute(() -> {
@@ -1,59 +0,0 @@
package com.youlai.boot.framework.web.ratelimit;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.util.Collections;
import java.util.UUID;
/**
* 滑动窗口限流 Lua 脚本(共享工具)
*
* @author Ray.Hao
* @since 4.4.0
*/
public final class SlidingWindowScript {
private SlidingWindowScript() {
throw new UnsupportedOperationException("工具类不允许实例化");
}
private static final DefaultRedisScript<Long> SCRIPT;
static {
SCRIPT = new DefaultRedisScript<>();
SCRIPT.setScriptText(
"local key = KEYS[1] " +
"local now = tonumber(ARGV[1]) " +
"local window = tonumber(ARGV[2]) " +
"local member = ARGV[3] " +
"redis.call('ZREMRANGEBYSCORE', key, 0, now - window) " +
"redis.call('ZADD', key, now, member) " +
"redis.call('PEXPIRE', key, window + 1000) " +
"return redis.call('ZCARD', key)"
);
SCRIPT.setResultType(Long.class);
}
/**
* 执行滑动窗口计数
*
* @param redisTemplate Redis 模板
* @param key 限流 Key(如 {@code rate_limit:ip:192.168.1.1})
* @param windowMs 窗口大小(毫秒)
* @return 当前窗口内请求数(包含本次)
*/
public static Long execute(RedisTemplate<String, Object> redisTemplate,
String key,
long windowMs) {
// 传 Long 而非 String,避免 Jackson 序列化器加双引号导致 Lua tonumber() 返回 nil
return redisTemplate.execute(
SCRIPT,
Collections.singletonList(key),
System.currentTimeMillis(),
windowMs,
UUID.randomUUID().toString()
);
}
}
@@ -13,6 +13,9 @@ import java.nio.charset.StandardCharsets;
/**
* 响应写入器
*
* @author Ray.Hao
* @since 4.13.0
*/
@Slf4j
public final class ResponseWriter {
@@ -54,6 +57,7 @@ public final class ResponseWriter {
private static int mapHttpStatus(ResultCode resultCode) {
return switch (resultCode) {
case AUTH_SERVICE_UNAVAILABLE -> HttpStatus.SERVICE_UNAVAILABLE.value();
case ACCESS_UNAUTHORIZED, ACCESS_TOKEN_INVALID, REFRESH_TOKEN_INVALID -> HttpStatus.UNAUTHORIZED.value();
case ACCESS_PERMISSION_EXCEPTION -> HttpStatus.FORBIDDEN.value();
case REQUEST_CONCURRENCY_LIMIT_EXCEEDED -> HttpStatus.TOO_MANY_REQUESTS.value();
@@ -13,8 +13,8 @@ import com.youlai.boot.framework.web.util.IPUtils;
import com.youlai.boot.module.form.model.form.FormAiGenerateForm;
import com.youlai.boot.module.form.model.form.FormDefinitionForm;
import com.youlai.boot.module.form.model.form.FormMenuForm;
import com.youlai.boot.module.form.model.query.FormDataPageQuery;
import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery;
import com.youlai.boot.module.form.model.query.FormDataQuery;
import com.youlai.boot.module.form.model.query.FormDefinitionQuery;
import com.youlai.boot.module.form.model.vo.FormDataVO;
import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO;
import com.youlai.boot.module.form.model.vo.FormMenuVO;
@@ -28,6 +28,7 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
@@ -53,7 +54,7 @@ public class FormController {
@GetMapping
@Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.LIST)
public PageResult<FormDefinitionPageVO> getFormDefinitionPage(
@Valid FormDefinitionPageQuery queryParams
@Valid FormDefinitionQuery queryParams
) {
Page<FormDefinitionPageVO> result = formDefinitionService.getFormDefinitionPage(queryParams);
return PageResult.success(result);
@@ -79,7 +80,7 @@ public class FormController {
@PreAuthorize("@ss.hasPerm('form:definition:create')")
@RepeatSubmit
@Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.INSERT)
public Result<Void> saveFormDefinition(@Valid @RequestBody FormDefinitionForm formData) {
public Result<Void> saveFormDefinition(@RequestBody @Validated(FormDefinitionForm.Create.class) FormDefinitionForm formData) {
boolean result = formDefinitionService.saveFormDefinition(formData);
return Result.judge(result);
}
@@ -90,7 +91,7 @@ public class FormController {
@Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.UPDATE)
public Result<Void> updateFormDefinition(
@Parameter(description = "表单ID") @PathVariable Long formId,
@RequestBody @Valid FormDefinitionForm formData
@RequestBody @Validated(FormDefinitionForm.Update.class) FormDefinitionForm formData
) {
boolean result = formDefinitionService.updateFormDefinition(formId, formData);
return Result.judge(result);
@@ -138,9 +139,6 @@ public class FormController {
return Result.success(renderVO);
}
//---------------------------------------------------
// 表单菜单相关接口(发布向导)
//---------------------------------------------------
@Operation(summary = "获取表单菜单配置(向导回显)")
@GetMapping("/{formId}/menu")
public Result<FormMenuVO> getFormMenu(
@@ -163,9 +161,7 @@ public class FormController {
return Result.judge(result);
}
//---------------------------------------------------
// 公开表单相关接口(匿名,Security 白名单 + Service 校验 is_public + IP 限流)
//---------------------------------------------------
// 公开访问须通过表单开关与 IP 限流校验
@Operation(summary = "获取公开表单渲染规则(匿名)")
@GetMapping("/public/{formKey}/render")
public Result<FormRenderVO> getPublicFormRender(
@@ -187,16 +183,13 @@ public class FormController {
return Result.judge(result);
}
//---------------------------------------------------
// 表单数据相关接口
//---------------------------------------------------
@Operation(summary = "表单数据分页列表")
@GetMapping("/{formKey}/data")
@PreAuthorize("@ss.hasPerm('form:data:list')")
@Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.LIST)
public PageResult<FormDataVO> getFormDataPage(
@Parameter(description = "表单唯一标识") @PathVariable String formKey,
@Valid FormDataPageQuery queryParams
@Valid FormDataQuery queryParams
) {
Page<FormDataVO> result = formDataService.getFormDataPage(formKey, queryParams);
return PageResult.success(result);
@@ -241,9 +234,7 @@ public class FormController {
return Result.success();
}
//---------------------------------------------------
// AI 辅助接口(未开启 AI 时调用返回业务异常)
//---------------------------------------------------
// AI 未启用时返回业务异常
@Operation(summary = "AI 生成表单规则")
@PostMapping("/ai-generate")
@@ -3,7 +3,7 @@ package com.youlai.boot.module.form.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.module.form.model.entity.FormData;
import com.youlai.boot.module.form.model.query.FormDataPageQuery;
import com.youlai.boot.module.form.model.query.FormDataQuery;
import com.youlai.boot.module.form.model.vo.FormDataVO;
import org.apache.ibatis.annotations.Mapper;
@@ -24,6 +24,6 @@ public interface FormDataMapper extends BaseMapper<FormData> {
* @param queryParams 查询参数
* @return 表单数据分页列表
*/
Page<FormDataVO> getFormDataPage(Page<FormDataVO> page, Long formId, FormDataPageQuery queryParams);
Page<FormDataVO> getFormDataPage(Page<FormDataVO> page, Long formId, FormDataQuery queryParams);
}
@@ -3,7 +3,7 @@ package com.youlai.boot.module.form.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.module.form.model.entity.FormDefinition;
import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery;
import com.youlai.boot.module.form.model.query.FormDefinitionQuery;
import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO;
import org.apache.ibatis.annotations.Mapper;
@@ -23,6 +23,6 @@ public interface FormDefinitionMapper extends BaseMapper<FormDefinition> {
* @param queryParams 查询参数
* @return 表单定义分页列表
*/
Page<FormDefinitionPageVO> getFormDefinitionPage(Page<FormDefinitionPageVO> page, FormDefinitionPageQuery queryParams);
Page<FormDefinitionPageVO> getFormDefinitionPage(Page<FormDefinitionPageVO> page, FormDefinitionQuery queryParams);
}
@@ -16,22 +16,34 @@ import lombok.Data;
@Data
public class FormDefinitionForm {
/**
* 创建校验组:表单标识、表单名称为必填
*/
public interface Create {
}
/**
* 更新校验组:只校验本次提交字段的格式,允许只提交规则或公开开关
*/
public interface Update {
}
@Schema(description = "表单ID", example = "1")
private Long id;
@Schema(description = "表单唯一标识(创建后不可修改)", example = "employee_onboarding")
@NotBlank(message = "表单标识不能为空")
@Size(max = 64, message = "表单标识长度不能超过64个字符")
@Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "表单标识须以小写字母开头,仅含小写字母、数字、下划线")
@NotBlank(message = "表单标识不能为空", groups = Create.class)
@Size(max = 64, message = "表单标识长度不能超过64个字符", groups = {Create.class, Update.class})
@Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "表单标识须以小写字母开头,仅含小写字母、数字、下划线", groups = {Create.class, Update.class})
private String formKey;
@Schema(description = "表单名称", example = "新员工入职信息采集")
@NotBlank(message = "表单名称不能为空")
@Size(max = 100, message = "表单名称长度不能超过100个字符")
@NotBlank(message = "表单名称不能为空", groups = Create.class)
@Size(max = 100, message = "表单名称长度不能超过100个字符", groups = {Create.class, Update.class})
private String formName;
@Schema(description = "表单描述")
@Size(max = 255, message = "表单描述长度不能超过255个字符")
@Size(max = 255, message = "表单描述长度不能超过255个字符", groups = {Create.class, Update.class})
private String description;
@Schema(description = "表单规则(form-create rule 数组 JSON 字符串,由设计器产出)")
@@ -44,7 +56,7 @@ public class FormDefinitionForm {
private Integer isPublic;
@Schema(description = "表单类型(normal通用表单 workflow工作流表单,缺省normal)", example = "normal")
@Pattern(regexp = "^(normal|workflow)$", message = "表单类型不合法")
@Pattern(regexp = "^(normal|workflow)$", message = "表单类型不合法", groups = {Create.class, Update.class})
private String category;
}
@@ -14,6 +14,6 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(description = "表单数据分页查询对象")
public class FormDataPageQuery extends BaseQuery {
public class FormDataQuery extends BaseQuery {
}
@@ -14,7 +14,7 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(description = "表单定义分页查询对象")
public class FormDefinitionPageQuery extends BaseQuery {
public class FormDefinitionQuery extends BaseQuery {
@Schema(description = "关键字(表单名称/标识)")
private String keywords;
@@ -1,7 +1,7 @@
package com.youlai.boot.module.form.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.module.form.model.query.FormDataPageQuery;
import com.youlai.boot.module.form.model.query.FormDataQuery;
import com.youlai.boot.module.form.model.vo.FormDataVO;
import java.util.List;
@@ -50,7 +50,7 @@ public interface FormDataService {
* @param queryParams 查询参数
* @return 表单数据分页列表
*/
Page<FormDataVO> getFormDataPage(String formKey, FormDataPageQuery queryParams);
Page<FormDataVO> getFormDataPage(String formKey, FormDataQuery queryParams);
/**
* 获取表单数据详情(只读回显)
@@ -5,7 +5,7 @@ import com.youlai.boot.common.model.Option;
import com.youlai.boot.module.form.model.entity.FormDefinition;
import com.youlai.boot.module.form.model.form.FormDefinitionForm;
import com.youlai.boot.module.form.model.form.FormMenuForm;
import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery;
import com.youlai.boot.module.form.model.query.FormDefinitionQuery;
import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO;
import com.youlai.boot.module.form.model.vo.FormMenuVO;
import com.youlai.boot.module.form.model.vo.FormRenderVO;
@@ -26,7 +26,7 @@ public interface FormDefinitionService {
* @param queryParams 查询参数
* @return 表单定义分页列表
*/
Page<FormDefinitionPageVO> getFormDefinitionPage(FormDefinitionPageQuery queryParams);
Page<FormDefinitionPageVO> getFormDefinitionPage(FormDefinitionQuery queryParams);
/**
* 按主键查询表单定义(供模块内回退取规则等场景)
@@ -13,7 +13,7 @@ import com.youlai.boot.module.form.mapper.FormSnapshotMapper;
import com.youlai.boot.module.form.model.entity.FormData;
import com.youlai.boot.module.form.model.entity.FormDefinition;
import com.youlai.boot.module.form.model.entity.FormSnapshot;
import com.youlai.boot.module.form.model.query.FormDataPageQuery;
import com.youlai.boot.module.form.model.query.FormDataQuery;
import com.youlai.boot.module.form.model.vo.FormDataVO;
import com.youlai.boot.module.form.service.FormDataService;
import com.youlai.boot.module.form.service.FormDefinitionService;
@@ -143,7 +143,7 @@ public class FormDataServiceImpl extends ServiceImpl<FormDataMapper, FormData> i
* @param queryParams 查询参数
*/
@Override
public Page<FormDataVO> getFormDataPage(String formKey, FormDataPageQuery queryParams) {
public Page<FormDataVO> getFormDataPage(String formKey, FormDataQuery queryParams) {
FormDefinition form = formDefinitionService.getByFormKey(formKey);
int pageNum = queryParams.getPageNum();
int pageSize = queryParams.getPageSize();
@@ -24,7 +24,7 @@ import com.youlai.boot.module.form.model.entity.FormDefinition;
import com.youlai.boot.module.form.model.entity.FormSnapshot;
import com.youlai.boot.module.form.model.form.FormDefinitionForm;
import com.youlai.boot.module.form.model.form.FormMenuForm;
import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery;
import com.youlai.boot.module.form.model.query.FormDefinitionQuery;
import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO;
import com.youlai.boot.module.form.model.vo.FormMenuVO;
import com.youlai.boot.module.form.model.vo.FormRenderVO;
@@ -82,7 +82,7 @@ public class FormDefinitionServiceImpl extends ServiceImpl<FormDefinitionMapper,
// 表单管理目录名称(顶级,dynamic-form.sql 预置):"表单中心"默认挂载其下,顶级入口聚合
private static final String FORM_ADMIN_CATALOG_NAME = "动态表单";
// 渲染缓存兜底 TTL:事件驱动清缓存外再设过期,防 DB 更新与删缓存间应用重启导致脏缓存永续
// 失效通知可能因进程中断丢失,以 TTL 限制旧规则的最长存留时间
private static final long RENDER_CACHE_TTL_MINUTES = 30;
/**
@@ -91,7 +91,7 @@ public class FormDefinitionServiceImpl extends ServiceImpl<FormDefinitionMapper,
* @param queryParams 查询参数
*/
@Override
public Page<FormDefinitionPageVO> getFormDefinitionPage(FormDefinitionPageQuery queryParams) {
public Page<FormDefinitionPageVO> getFormDefinitionPage(FormDefinitionQuery queryParams) {
int pageNum = queryParams.getPageNum();
int pageSize = queryParams.getPageSize();
return this.baseMapper.getFormDefinitionPage(new Page<>(pageNum, pageSize), queryParams);
@@ -409,7 +409,7 @@ public class FormDefinitionServiceImpl extends ServiceImpl<FormDefinitionMapper,
}
}
// 组装菜单:类型 M,指向通用承载页;已生成过时携带原菜单ID走更新语义(幂等)
// 已生成过菜单时更新原记录,重复发布不创建新菜单
String routeName = "FormRender" + StrUtil.upperFirst(StrUtil.toCamelCase(form.getFormKey(), '_'));
MenuForm menuFormData = new MenuForm();
menuFormData.setId(form.getMenuId());
@@ -423,11 +423,13 @@ public class FormDefinitionServiceImpl extends ServiceImpl<FormDefinitionMapper,
menuFormData.setVisible(1);
menuFormData.setSort(1);
// keepAlive 不开启:多个表单菜单共用 render 组件,组件级缓存会导致切换表单时回显错乱
boolean result = menuService.saveMenu(menuFormData);
boolean result = form.getMenuId() == null
? menuService.saveMenu(menuFormData)
: menuService.updateMenu(form.getMenuId(), menuFormData);
if (!result) {
return false;
}
// saveMenu 内部 saveOrUpdate 不回写表单对象主键,按全局唯一路由名称反查菜单ID
// 保存不回写表单对象主键,按全局唯一路由名称查询菜单ID
Menu menu = menuService.getOne(new LambdaQueryWrapper<Menu>()
.eq(Menu::getRouteName, routeName)
.last("LIMIT 1")
@@ -578,9 +580,7 @@ public class FormDefinitionServiceImpl extends ServiceImpl<FormDefinitionMapper,
.toList();
}
//---------------------------------------------------
// AI 辅助:未开启 AI 时调用返回业务异常
//---------------------------------------------------
// AI 未启用时返回业务异常
/**
* 用 AI 把需求描述转成 form-create 规则
@@ -8,7 +8,7 @@ import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.module.workflow.model.form.StartProcessForm;
import com.youlai.boot.module.workflow.model.query.WorkflowInstancePageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowInstanceQuery;
import com.youlai.boot.module.workflow.model.vo.InstanceDetailVO;
import com.youlai.boot.module.workflow.model.vo.InstancePageVO;
import com.youlai.boot.module.workflow.model.vo.ProcessDiagramVO;
@@ -48,7 +48,7 @@ public class WorkflowInstanceController {
@Operation(summary = "我的流程分页列表")
@GetMapping
@Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST, title = "我的流程")
public PageResult<InstancePageVO> getInstancePage(@Valid WorkflowInstancePageQuery queryParams) {
public PageResult<InstancePageVO> getInstancePage(@Valid WorkflowInstanceQuery queryParams) {
Page<InstancePageVO> result = workflowInstanceService.getInstancePage(queryParams);
return PageResult.success(result);
}
@@ -9,7 +9,7 @@ import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.module.workflow.model.form.ModelForm;
import com.youlai.boot.module.workflow.model.form.ModelXmlForm;
import com.youlai.boot.module.workflow.model.query.WorkflowModelPageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowModelQuery;
import com.youlai.boot.module.workflow.model.vo.ModelVO;
import com.youlai.boot.module.workflow.model.vo.ModelXmlVO;
import com.youlai.boot.module.workflow.service.WorkflowDemoService;
@@ -45,7 +45,7 @@ public class WorkflowModelController {
@GetMapping
@PreAuthorize("@ss.hasPerm('workflow:model:list')")
@Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST)
public PageResult<ModelVO> getModelPage(@Valid WorkflowModelPageQuery queryParams) {
public PageResult<ModelVO> getModelPage(@Valid WorkflowModelQuery queryParams) {
Page<ModelVO> result = workflowModelService.getModelPage(queryParams);
return PageResult.success(result);
}
@@ -9,7 +9,7 @@ import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.module.workflow.model.form.CompleteTaskForm;
import com.youlai.boot.module.workflow.model.form.RejectTaskForm;
import com.youlai.boot.module.workflow.model.query.WorkflowTaskPageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowTaskQuery;
import com.youlai.boot.module.workflow.model.vo.DoneTaskVO;
import com.youlai.boot.module.workflow.model.vo.RejectTargetVO;
import com.youlai.boot.module.workflow.model.vo.TaskDetailVO;
@@ -43,7 +43,7 @@ public class WorkflowTaskController {
@Operation(summary = "待办任务分页列表")
@GetMapping("/todo")
@Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST, title = "待办任务")
public PageResult<TodoTaskVO> getTodoTaskPage(@Valid WorkflowTaskPageQuery queryParams) {
public PageResult<TodoTaskVO> getTodoTaskPage(@Valid WorkflowTaskQuery queryParams) {
Page<TodoTaskVO> result = workflowTaskService.getTodoTaskPage(queryParams);
return PageResult.success(result);
}
@@ -51,7 +51,7 @@ public class WorkflowTaskController {
@Operation(summary = "已办任务分页列表")
@GetMapping("/done")
@Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST, title = "已办任务")
public PageResult<DoneTaskVO> getDoneTaskPage(@Valid WorkflowTaskPageQuery queryParams) {
public PageResult<DoneTaskVO> getDoneTaskPage(@Valid WorkflowTaskQuery queryParams) {
Page<DoneTaskVO> result = workflowTaskService.getDoneTaskPage(queryParams);
return PageResult.success(result);
}
@@ -14,7 +14,7 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(description = "流程实例分页查询对象")
public class WorkflowInstancePageQuery extends BaseQuery {
public class WorkflowInstanceQuery extends BaseQuery {
@Schema(description = "关键字(流程定义名称)")
private String keywords;
@@ -14,7 +14,7 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(description = "流程模型分页查询对象")
public class WorkflowModelPageQuery extends BaseQuery {
public class WorkflowModelQuery extends BaseQuery {
@Schema(description = "关键字(模型名称)")
private String keywords;
@@ -14,7 +14,7 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@Schema(description = "任务分页查询对象")
public class WorkflowTaskPageQuery extends BaseQuery {
public class WorkflowTaskQuery extends BaseQuery {
@Schema(description = "关键字(任务名称)")
private String keywords;
@@ -2,7 +2,7 @@ package com.youlai.boot.module.workflow.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.module.workflow.model.form.StartProcessForm;
import com.youlai.boot.module.workflow.model.query.WorkflowInstancePageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowInstanceQuery;
import com.youlai.boot.module.workflow.model.vo.InstanceDetailVO;
import com.youlai.boot.module.workflow.model.vo.InstancePageVO;
import com.youlai.boot.module.workflow.model.vo.ProcessDiagramVO;
@@ -29,7 +29,7 @@ public interface WorkflowInstanceService {
* @param queryParams 查询参数
* @return 分页结果
*/
Page<InstancePageVO> getInstancePage(WorkflowInstancePageQuery queryParams);
Page<InstancePageVO> getInstancePage(WorkflowInstanceQuery queryParams);
/**
* 获取流程图数据(BPMN XML + 已办/进行中节点,bpmn-js 高亮渲染)
@@ -3,7 +3,7 @@ package com.youlai.boot.module.workflow.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.module.workflow.model.form.ModelForm;
import com.youlai.boot.module.workflow.model.form.ModelXmlForm;
import com.youlai.boot.module.workflow.model.query.WorkflowModelPageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowModelQuery;
import com.youlai.boot.module.workflow.model.vo.ModelVO;
import com.youlai.boot.module.workflow.model.vo.ModelXmlVO;
@@ -26,7 +26,7 @@ public interface WorkflowModelService {
* @param queryParams 查询参数
* @return 分页结果
*/
Page<ModelVO> getModelPage(WorkflowModelPageQuery queryParams);
Page<ModelVO> getModelPage(WorkflowModelQuery queryParams);
/**
* 新增流程模型(内置开始-审批-结束模板,设计器开箱即画)
@@ -3,7 +3,7 @@ package com.youlai.boot.module.workflow.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.module.workflow.model.form.CompleteTaskForm;
import com.youlai.boot.module.workflow.model.form.RejectTaskForm;
import com.youlai.boot.module.workflow.model.query.WorkflowTaskPageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowTaskQuery;
import com.youlai.boot.module.workflow.model.vo.DoneTaskVO;
import com.youlai.boot.module.workflow.model.vo.RejectTargetVO;
import com.youlai.boot.module.workflow.model.vo.TaskDetailVO;
@@ -25,7 +25,7 @@ public interface WorkflowTaskService {
* @param queryParams 查询参数
* @return 分页结果
*/
Page<TodoTaskVO> getTodoTaskPage(WorkflowTaskPageQuery queryParams);
Page<TodoTaskVO> getTodoTaskPage(WorkflowTaskQuery queryParams);
/**
* 已办任务分页列表(当前用户已办理的任务)
@@ -33,7 +33,7 @@ public interface WorkflowTaskService {
* @param queryParams 查询参数
* @return 分页结果
*/
Page<DoneTaskVO> getDoneTaskPage(WorkflowTaskPageQuery queryParams);
Page<DoneTaskVO> getDoneTaskPage(WorkflowTaskQuery queryParams);
/**
* 获取待办任务详情(发起表单只读回显 + 审批记录)
@@ -9,7 +9,7 @@ import com.youlai.boot.module.form.model.vo.FormDataVO;
import com.youlai.boot.module.form.service.FormDataService;
import com.youlai.boot.module.workflow.enums.InstanceStatusEnum;
import com.youlai.boot.module.workflow.model.form.StartProcessForm;
import com.youlai.boot.module.workflow.model.query.WorkflowInstancePageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowInstanceQuery;
import com.youlai.boot.module.workflow.model.vo.InstanceDetailVO;
import com.youlai.boot.module.workflow.model.vo.InstancePageVO;
import com.youlai.boot.module.workflow.model.vo.ProcessDiagramVO;
@@ -109,7 +109,7 @@ public class WorkflowInstanceServiceImpl implements WorkflowInstanceService {
* @param queryParams 查询参数
*/
@Override
public Page<InstancePageVO> getInstancePage(WorkflowInstancePageQuery queryParams) {
public Page<InstancePageVO> getInstancePage(WorkflowInstanceQuery queryParams) {
HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery()
.startedBy(SecurityUtils.getUsername());
if (StrUtil.isNotBlank(queryParams.getKeywords())) {
@@ -10,7 +10,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.module.workflow.model.form.ModelForm;
import com.youlai.boot.module.workflow.model.form.ModelXmlForm;
import com.youlai.boot.module.workflow.model.query.WorkflowModelPageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowModelQuery;
import com.youlai.boot.module.workflow.model.vo.ModelVO;
import com.youlai.boot.module.workflow.model.vo.ModelXmlVO;
import com.youlai.boot.module.workflow.service.WorkflowModelService;
@@ -111,7 +111,7 @@ public class WorkflowModelServiceImpl implements WorkflowModelService {
* @param queryParams 查询参数
*/
@Override
public Page<ModelVO> getModelPage(WorkflowModelPageQuery queryParams) {
public Page<ModelVO> getModelPage(WorkflowModelQuery queryParams) {
ModelQuery query = repositoryService.createModelQuery();
if (StrUtil.isNotBlank(queryParams.getKeywords())) {
query.modelNameLike("%" + queryParams.getKeywords() + "%");
@@ -14,7 +14,7 @@ import com.youlai.boot.module.form.service.FormDataService;
import com.youlai.boot.module.form.util.FormRuleValidator;
import com.youlai.boot.module.workflow.model.form.CompleteTaskForm;
import com.youlai.boot.module.workflow.model.form.RejectTaskForm;
import com.youlai.boot.module.workflow.model.query.WorkflowTaskPageQuery;
import com.youlai.boot.module.workflow.model.query.WorkflowTaskQuery;
import com.youlai.boot.module.workflow.model.vo.ApprovalHistoryVO;
import com.youlai.boot.module.workflow.model.vo.DoneTaskVO;
import com.youlai.boot.module.workflow.model.vo.RejectTargetVO;
@@ -86,7 +86,7 @@ public class WorkflowTaskServiceImpl implements WorkflowTaskService {
* @param queryParams 查询参数
*/
@Override
public Page<TodoTaskVO> getTodoTaskPage(WorkflowTaskPageQuery queryParams) {
public Page<TodoTaskVO> getTodoTaskPage(WorkflowTaskQuery queryParams) {
TaskQuery query = this.createCandidateTaskQuery();
if (StrUtil.isNotBlank(queryParams.getKeywords())) {
query.taskNameLike("%" + queryParams.getKeywords() + "%");
@@ -130,7 +130,7 @@ public class WorkflowTaskServiceImpl implements WorkflowTaskService {
* @param queryParams 查询参数
*/
@Override
public Page<DoneTaskVO> getDoneTaskPage(WorkflowTaskPageQuery queryParams) {
public Page<DoneTaskVO> getDoneTaskPage(WorkflowTaskQuery queryParams) {
HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
.taskAssignee(SecurityUtils.getUsername()).finished();
if (StrUtil.isNotBlank(queryParams.getKeywords())) {
@@ -386,9 +386,7 @@ public class WorkflowTaskServiceImpl implements WorkflowTaskService {
.collect(Collectors.toMap(ProcessInstance::getId, instance -> instance));
}
//---------------------------------------------------
// AI 辅助:未开启 AI 时调用返回业务异常
//---------------------------------------------------
// AI 未启用时返回业务异常
/**
* 用 AI 汇总表单数据与审批记录,生成审批摘要
@@ -0,0 +1,60 @@
package com.youlai.boot.support.realtime;
import com.youlai.boot.support.realtime.config.RealtimeProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* 调度实时连接的心跳与授权维护
*
* @author Ray.Hao
* @since 4.13.0
*/
@Slf4j
@Component
public class RealtimeMaintenanceTask {
private final ScheduledExecutorService scheduler;
private final RealtimeSessionManager sessions;
private final RealtimeProperties properties;
private ScheduledFuture<?> task;
public RealtimeMaintenanceTask(@Qualifier("realtimeScheduler") ScheduledExecutorService scheduler,
RealtimeSessionManager sessions, RealtimeProperties properties) {
this.scheduler = scheduler;
this.sessions = sessions;
this.properties = properties;
}
/**
* 启动定期维护任务
*/
@PostConstruct
public void start() {
if (!properties.isEnabled()) {
return;
}
task = scheduler.scheduleWithFixedDelay(() -> {
try {
sessions.maintain();
} catch (Exception exception) {
log.error("Realtime maintenance failed", exception);
}
}, 1, 1, TimeUnit.SECONDS);
}
/**
* 取消维护任务
*/
@PreDestroy
public void stop() {
if (task != null) {
task.cancel(false);
}
}
}
@@ -0,0 +1,129 @@
package com.youlai.boot.support.realtime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
/**
* 每连接一个发送者;排队帧和正在写出的帧都计入内存预算
*
* @author Ray.Hao
* @since 4.13.0
*/
@Slf4j
@Component
public class RealtimeMessageSender {
private static final int MAX_SESSION_BYTES = 32_768;
private static final int MAX_SESSION_MESSAGES = 32;
private final Executor executor;
public RealtimeMessageSender(@Qualifier("realtimeSenderExecutor") Executor executor) {
this.executor = executor;
}
/**
* 待发送文本及其预算占用
*/
record Frame(String text, int bytes) {
/**
* 按 UTF-8 字节数计算帧的预算占用
*/
static Frame of(String text) {
return new Frame(text, text.getBytes(StandardCharsets.UTF_8).length);
}
}
/**
* 在连接预算内入队,同一连接只启动一个发送者
*/
boolean enqueue(RealtimeSession session, Frame frame, Runnable onFailure) {
boolean start;
synchronized (session) {
if (session.closed) {
return false;
}
if (session.bufferedMessages >= MAX_SESSION_MESSAGES
|| session.bufferedBytes + frame.bytes() > MAX_SESSION_BYTES) {
return false;
}
session.queue.addLast(frame);
session.bufferedBytes += frame.bytes();
session.bufferedMessages++;
start = !session.draining;
session.draining = true;
}
if (start) {
submit(session, onFailure);
}
return true;
}
/**
* 投递发送任务,线程池拒绝时清理连接
*/
private void submit(RealtimeSession session, Runnable onFailure) {
try {
executor.execute(() -> drain(session, onFailure));
} catch (RejectedExecutionException exception) {
synchronized (session) {
session.draining = false;
}
onFailure.run();
}
}
/**
* 串行发送连接中的排队帧,并归还预算
*/
private void drain(RealtimeSession session, Runnable onFailure) {
// 每轮最多发送 16 帧后让出线程,避免单条连接长期占用发送池
for (int count = 0; count < 16; count++) {
Frame frame;
synchronized (session) {
frame = session.closed ? null : session.queue.pollFirst();
if (frame == null) {
session.draining = false;
return;
}
}
boolean failed = false;
try {
session.transport.sendMessage(new TextMessage(frame.text()));
} catch (Exception exception) {
failed = true;
log.debug("Realtime write failed: {}", exception.getClass().getSimpleName());
} finally {
// 正在写出的帧在此结算,关闭连接只释放尚未发送的队列
synchronized (session) {
session.bufferedBytes -= frame.bytes();
session.bufferedMessages--;
}
}
if (failed) {
synchronized (session) {
session.draining = false;
}
onFailure.run();
return;
}
}
submit(session, onFailure);
}
/**
* 只释放排队帧,正在写出的帧由 drain 的 finally 结算
*/
void discardQueued(RealtimeSession session) {
synchronized (session) {
Frame frame;
while ((frame = session.queue.pollFirst()) != null) {
session.bufferedBytes -= frame.bytes();
session.bufferedMessages--;
}
}
}
}
@@ -0,0 +1,79 @@
package com.youlai.boot.support.realtime;
import com.youlai.boot.support.realtime.config.RealtimeProperties;
import com.youlai.boot.support.realtime.protocol.RealtimeServerMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.function.BiFunction;
/**
* 异步广播与分批发送业务变更提示
*
* @author Ray.Hao
* @since 4.13.0
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class RealtimeService {
private static final int RECIPIENT_BATCH_SIZE = 100;
private final RealtimeSessionManager sessions;
private final RealtimeProperties properties;
private final Semaphore deliveryJobs = new Semaphore(2);
/**
* 向订阅指定主题的连接异步广播消息
*/
public void broadcast(String topic, String type, Object payload) {
if (properties.isEnabled()) {
var message = RealtimeServerMessage.create(type, payload);
sessions.submitMaintenance(() -> sessions.broadcast(topic, message));
}
}
/**
* 分批投递失效提示,批次之间重新排队让出线程
* loadRecipients 按 userId 升序查询游标之后的用户,返回数不得超过传入的 limit
*/
public void sendBatches(String type, Object payload, BiFunction<Long, Integer, List<Long>> loadRecipients) {
if (!properties.isEnabled()) {
return;
}
if (!deliveryJobs.tryAcquire()) {
log.warn("Realtime delivery dropped: audience queue full");
return;
}
submitBatch(loadRecipients, RealtimeServerMessage.create(type, payload), 0);
}
/**
* 提交一批收件人投递,结束或拒绝时释放任务配额
*/
private void submitBatch(BiFunction<Long, Integer, List<Long>> loader,
RealtimeServerMessage message, long afterUserId) {
if (!sessions.submitMaintenance(() -> {
boolean continued = false;
try {
List<Long> recipients = loader.apply(afterUserId, RECIPIENT_BATCH_SIZE);
if (!recipients.isEmpty()) {
sessions.sendToUsers(recipients, message);
}
if (recipients.size() == RECIPIENT_BATCH_SIZE) {
continued = true;
submitBatch(loader, message, recipients.get(recipients.size() - 1));
}
} catch (Exception exception) {
log.warn("Realtime audience delivery failed: {}", exception.getClass().getSimpleName());
} finally {
if (!continued) {
deliveryJobs.release();
}
}
})) {
deliveryJobs.release();
}
}
}
@@ -0,0 +1,71 @@
package com.youlai.boot.support.realtime;
import com.youlai.boot.support.realtime.security.RealtimeTicketService.TicketGrant;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Set;
/**
* 可变连接状态由本对象的监视器保护,锁内不执行网络或存储操作
*
* @author Ray.Hao
* @since 4.13.0
*/
final class RealtimeSession {
final WebSocketSession transport;
final Long userId;
final String instanceKey;
final RealtimeSessionManager.Reservation reservation;
final ArrayDeque<RealtimeMessageSender.Frame> queue = new ArrayDeque<>();
private String accessToken;
final Set<String> topics;
final Instant authExpiresAt;
// 间隔判断使用单调时钟纳秒;协议中的绝对到期时间使用 Instant
long lastVerifiedAt = System.nanoTime();
long lastPongAt = System.nanoTime();
long nextPingAt = lastPongAt + java.util.concurrent.TimeUnit.SECONDS.toNanos(25);
String pendingPingId;
long nextVerifyAt = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5)
+ java.util.concurrent.ThreadLocalRandom.current().nextLong(java.util.concurrent.TimeUnit.SECONDS.toNanos(10));
// 预算包含排队和正在写出的帧,由发送者分别结算
int bufferedBytes;
int bufferedMessages;
int inboundMessages;
long inboundWindow = System.nanoTime();
boolean draining;
// closed 停止业务收发;terminated 表示底层连接结束,可释放配额
boolean closed;
boolean terminated;
boolean verifying;
boolean closeRunning;
int closeAttempts;
CloseStatus closeStatus = CloseStatus.NORMAL;
RealtimeSession(WebSocketSession transport, TicketGrant grant,
RealtimeSessionManager.Reservation reservation, Instant authExpiresAt) {
this.transport = transport;
this.userId = grant.userId();
this.instanceKey = grant.userId() + ":" + grant.clientInstanceId();
this.accessToken = grant.accessToken();
this.topics = grant.topics();
this.reservation = reservation;
this.authExpiresAt = authExpiresAt;
}
synchronized String accessToken() {
return accessToken;
}
/**
* 清除连接持有的认证凭证
*/
synchronized void forgetCredential() {
accessToken = null;
}
@Override
public String toString() {
return "RealtimeSession[transport=" + transport.getId() + "]";
}
}
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more