From 0a99d1c2c8f4169e7207fa6752d3f8e970698929 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=B8=96=E7=90=B3?= Date: Mon, 16 Dec 2024 17:00:32 +0800 Subject: [PATCH] =?UTF-8?q?[feat]:=E7=94=A8=E6=88=B7=E5=BE=AE=E4=BF=A1?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/service/impl/SysUserServiceImpl.java | 23 +++- .../token/TencentAuthenticationToken.java | 32 +++++ .../com/central/common/feign/UserService.java | 8 ++ .../fallback/UserServiceFallbackFactory.java | 6 + .../com/central/common/model/SysUser.java | 2 +- .../main/resources/application-dev.properties | 10 +- .../src/main/resources/bootstrap.properties | 4 +- .../nacos/conf/application.properties | 8 +- .../config/AuthorizationServerConfig.java | 6 +- .../oauth/service/ZltUserDetailsService.java | 6 + .../service/impl/UserDetailServiceImpl.java | 8 ++ .../TencentAuthenticationConverter.java | 52 ++++++++ .../TencentAuthenticationProvider.java | 124 ++++++++++++++++++ zlt-uaa/src/main/resources/application.yml | 6 +- 14 files changed, 279 insertions(+), 16 deletions(-) create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java create mode 100644 zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java create mode 100644 zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java index 47cfa233..bc4abda8 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java +++ b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java @@ -60,8 +60,8 @@ public class SysUserServiceImpl extends SuperServiceImpl } @Override - public SysUser findByOpenId(String username) { - SysUser sysUser = this.selectByOpenId(username); + public SysUser findByOpenId(String openId) { + SysUser sysUser = this.selectByOpenId(openId); setUserPermission(sysUser); return sysUser; } @@ -73,6 +73,23 @@ public class SysUserServiceImpl extends SuperServiceImpl return sysUser; } + @Override + public SysUser findByWxOpenid(String wxOpenid) throws Exception { + SysUser sysUser = this.selectByOpenId(wxOpenid); + if (sysUser.getId() == null) { + sysUser.setOpenId(wxOpenid); + sysUser.setUsername(wxOpenid); + sysUser.setType(UserType.APP.name()); + sysUser.setPassword(wxOpenid); + sysUser.setEnabled(Boolean.TRUE); + } + String username = sysUser.getUsername(); + boolean result = super.saveOrUpdateIdempotency(sysUser, lock + , LOCK_KEY_USERNAME+username, new QueryWrapper().eq("username", username) + , username+"已存在"); + return result ? sysUser : new SysUser(); + } + @Override public void setUserPermission(SysUser sysUser) { if (sysUser != null) { @@ -262,4 +279,4 @@ public class SysUserServiceImpl extends SuperServiceImpl } return sysUserExcels; } -} \ No newline at end of file +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java new file mode 100644 index 00000000..6a0a2837 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TencentAuthenticationToken.java @@ -0,0 +1,32 @@ +package com.central.oauth2.common.token; + +import lombok.Getter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.AuthorizationGrantType; + +import java.util.Collection; + +/** + * @author: lsl + * @date: 2024/12/16 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Getter +public class TencentAuthenticationToken extends BaseAuthenticationToken { + public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("tencent"); + private final Object principal; + + public TencentAuthenticationToken(String code) { + super(GRANT_TYPE); + this.principal = code; + super.setAuthenticated(true); + } + + public TencentAuthenticationToken(UserDetails user, Collection authorities) { + super(authorities); + this.principal = user; + } +} diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java index fbef509d..aa68e520 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java @@ -51,6 +51,14 @@ public interface UserService { @GetMapping(value = "/users-anon/openId", params = "openId") SysUser findByOpenId(@RequestParam("openId") String openId); + /** + * 根据OpenId查询用户信息 + * + * @param openId openId + */ + @GetMapping(value = "/users-anon/wxOpenId", params = "openId") + SysUser findByWxOpenId(@RequestParam("openId") String openId); + /** * 获取带角色的用户信息 diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java index eb83c655..805179c9 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java @@ -44,6 +44,12 @@ public class UserServiceFallbackFactory implements FallbackFactory return new SysUser(); } + @Override + public SysUser findByWxOpenId(String openId) { + log.error("通过wxOpenId查询用户异常:{}", openId, throwable); + return new SysUser(); + } + /** * 获取带角色的用户信息 * diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java index bd90f82a..044d18a0 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java @@ -11,7 +11,7 @@ import lombok.EqualsAndHashCode; /** * @author zlt - * 用户实体 + * 系统用户实体 */ @Data @EqualsAndHashCode(callSuper = false) diff --git a/zlt-config/src/main/resources/application-dev.properties b/zlt-config/src/main/resources/application-dev.properties index 80bcb0ac..54e897de 100644 --- a/zlt-config/src/main/resources/application-dev.properties +++ b/zlt-config/src/main/resources/application-dev.properties @@ -1,12 +1,14 @@ ########################## 统一变量配置 ########################## ##### 数据库配置 -zlt.datasource.ip=192.168.28.130 +zlt.datasource.ip=127.0.0.1 zlt.datasource.username=root -zlt.datasource.password=1q2w3e4r +zlt.datasource.password=root ##### redis配置 -spring.data.redis.host=192.168.28.130 +spring.data.redis.host=192.168.2.20 spring.data.redis.port=6379 +spring.data.redis.password=ikingtec123456 +spring.data.redis.database=7 spring.data.redis.timeout=5000 ##### elasticsearch配置 @@ -37,4 +39,4 @@ zlt.ribbon.isolation.enabled=false mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl # 开启版本路由 -#zlt.loadbalance.isolation.enabled=true \ No newline at end of file +#zlt.loadbalance.isolation.enabled=true diff --git a/zlt-config/src/main/resources/bootstrap.properties b/zlt-config/src/main/resources/bootstrap.properties index 6723ea5e..a67fd4a8 100644 --- a/zlt-config/src/main/resources/bootstrap.properties +++ b/zlt-config/src/main/resources/bootstrap.properties @@ -3,7 +3,7 @@ spring.profiles.active=dev ##### nacos(注册中心和配置中心)地址 -spring.cloud.nacos.server-addr=192.168.28.130:8848 +spring.cloud.nacos.server-addr=192.168.4.44:8848 spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos spring.cloud.nacos.config.file-extension=yml @@ -15,4 +15,4 @@ management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always ##### 允许bean覆盖 -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true diff --git a/zlt-register/nacos/conf/application.properties b/zlt-register/nacos/conf/application.properties index 3f84c38f..ee30929f 100644 --- a/zlt-register/nacos/conf/application.properties +++ b/zlt-register/nacos/conf/application.properties @@ -33,12 +33,12 @@ server.port=8848 # spring.datasource.platform=mysql ### Count of DB: -# db.num=1 +db.num=1 ### Connect URL of DB: -# db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC -# db.user.0=nacos -# db.password.0=nacos +db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC +db.user.0=root +db.password.0=root ### Connection pool configuration: hikariCP db.pool.config.connectionTimeout=30000 diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java index 51c98439..19435a10 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java +++ b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java @@ -14,6 +14,8 @@ import com.central.oauth.support.password.PasswordAuthenticationConverter; import com.central.oauth.support.password.PasswordAuthenticationProvider; import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationConverter; import com.central.oauth.support.passwordCode.PasswordCodeAuthenticationProvider; +import com.central.oauth.support.tencent.TencentAuthenticationConverter; +import com.central.oauth.support.tencent.TencentAuthenticationProvider; import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector; import com.central.oauth2.common.component.CustomBearerTokenResolver; import com.central.oauth2.common.config.BaseSecurityConfig; @@ -108,6 +110,7 @@ public class AuthorizationServerConfig { .authenticationProvider(new PasswordCodeAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder, validateCodeService)) .authenticationProvider(new OpenIdAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory)) .authenticationProvider(new MobileAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory, passwordEncoder)) + .authenticationProvider(new TencentAuthenticationProvider(authorizationService, tokenGenerator, userDetailsServiceFactory)) ) // 开启OpenID Connect 1.0协议相关端点 .oidc(Customizer.withDefaults()) @@ -146,6 +149,7 @@ public class AuthorizationServerConfig { new PasswordAuthenticationConverter(), new PasswordCodeAuthenticationConverter(), new OpenIdAuthenticationConverter(), - new MobileAuthenticationConverter())); + new MobileAuthenticationConverter(), + new TencentAuthenticationConverter())); } } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java index a3148273..fca81721 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java @@ -31,4 +31,10 @@ public interface ZltUserDetailsService extends UserDetailsService { * @param userId 用户id/openId */ UserDetails loadUserByUserId(String userId) throws UsernameNotFoundException; + + /** + * 根据微信用户id/openId查询用户 + * @param wxOpenId 用户id/openId + */ + UserDetails loadUserByWxOpenId(String wxOpenId) throws UsernameNotFoundException; } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java index 51159368..50307170 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java @@ -9,6 +9,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -49,6 +50,13 @@ public class UserDetailServiceImpl implements ZltUserDetailsService { return LoginUserUtils.getLoginAppUser(sysUser); } + @Override + public UserDetails loadUserByWxOpenId(String wxOpenId) throws UsernameNotFoundException { + SysUser sysUser = userService.findByWxOpenId(wxOpenId); + checkUser(sysUser); + return LoginUserUtils.getLoginAppUser(sysUser); + } + @Override public UserDetails loadUserByMobile(String mobile) { SysUser sysUser = userService.findByMobile(mobile); diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java new file mode 100644 index 00000000..acc70897 --- /dev/null +++ b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationConverter.java @@ -0,0 +1,52 @@ +package com.central.oauth.support.tencent; + +import com.alibaba.fastjson.JSONObject; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.central.oauth.exception.CustomOAuth2AuthenticationException; +import com.central.oauth.support.base.BaseAuthenticationConverter; +import com.central.oauth.utils.OAuthEndpointUtils; +import com.central.oauth2.common.token.BaseAuthenticationToken; +import com.central.oauth2.common.token.TencentAuthenticationToken; +import org.springframework.beans.BeanUtils; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.util.Assert; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author: zlt + * @date: 2023/11/18 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +public class TencentAuthenticationConverter extends BaseAuthenticationConverter { + + @Override + protected String supportGrantType() { + return TencentAuthenticationToken.GRANT_TYPE.getValue(); + } + + @Override + protected List paramNames() { + return List.of(OAuth2ParameterNames.CODE); + } + + @Override + protected BaseAuthenticationToken getToken(MultiValueMap parameters) { + String code = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.CODE); + return new TencentAuthenticationToken(code); + } + + + +} diff --git a/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java new file mode 100644 index 00000000..16eeec5d --- /dev/null +++ b/zlt-uaa/src/main/java/com/central/oauth/support/tencent/TencentAuthenticationProvider.java @@ -0,0 +1,124 @@ +package com.central.oauth.support.tencent; + +import com.central.oauth.exception.CustomOAuth2AuthenticationException; +import com.central.oauth.service.IValidateCodeService; +import com.central.oauth.service.impl.UserDetailServiceFactory; +import com.central.oauth.support.base.BaseAuthenticationProvider; +import com.central.oauth2.common.token.TencentAuthenticationToken; +import lombok.Getter; +import lombok.Setter; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.OAuth2Token; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator; +import org.springframework.util.Assert; +import org.springframework.web.client.RestTemplate; + +import java.util.HashMap; +import java.util.Map; + +/** + * 微信小程序登录 provider + * + * @author lsl + * @version 1.0 + * @date 2024/12/16 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Setter +@Getter +public class TencentAuthenticationProvider extends BaseAuthenticationProvider { + private final UserDetailServiceFactory userDetailsServiceFactory; + + public TencentAuthenticationProvider(OAuth2AuthorizationService authorizationService + , OAuth2TokenGenerator tokenGenerator + , UserDetailServiceFactory userDetailsServiceFactory) { + super(authorizationService, tokenGenerator); + Assert.notNull(userDetailsServiceFactory, "userDetailsServiceFactory cannot be null"); + this.userDetailsServiceFactory = userDetailsServiceFactory; + } + + @Override + public boolean supports(Class authentication) { + return TencentAuthenticationToken.class.isAssignableFrom(authentication); + } + + @Override + protected Authentication getPrincipal(Authentication authentication) { + TencentAuthenticationToken authToken = (TencentAuthenticationToken) authentication; + + String code = (String) authToken.getPrincipal(); + Map wxLoginResult = getWxOpenId(code); + + UserDetails userDetails; + try { + userDetails = userDetailsServiceFactory.getService(authToken).loadUserByWxOpenId(wxLoginResult.get("openid").toString()); + + } catch (AuthenticationException e) { + throw new CustomOAuth2AuthenticationException(e.getMessage()); + } + if (userDetails == null) { + + throw new CustomOAuth2AuthenticationException("用户登录信息待处理,请重新登录"); + } + return new TencentAuthenticationToken(userDetails, userDetails.getAuthorities()); + } + + @Override + protected AuthorizationGrantType grantType() { + return TencentAuthenticationToken.GRANT_TYPE; + } + + /** + * 微信小程序第三方登录,或微信APP安全登录 + * + * @param code 小程序code + * @return + */ + private Map getWxOpenId(String code) { + + if (code == null || code.isEmpty()) { + throw new CustomOAuth2AuthenticationException("Code cannot be null or empty"); + } + + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.set("Content-Type", "application/json"); + + Map params = new HashMap<>(); + params.put("appid", "appId"); + params.put("secret", "appSecret"); + params.put("js_code", code); + params.put("grant_type", "authorization_code"); + + HttpEntity> entity = new HttpEntity<>(params, headers); + ResponseEntity response = restTemplate.exchange( + "WX_LOGIN_URL", + HttpMethod.POST, + entity, + Map.class + ); + + if (response.getStatusCode().is2xxSuccessful()) { + Map body = response.getBody(); + if (body != null && body.containsKey("openid")) { + return body; + } else { + throw new CustomOAuth2AuthenticationException("Failed to obtain OpenID token"); + } + } else { + throw new CustomOAuth2AuthenticationException("Request failed: " + response.getStatusCode()); + } + + } +} diff --git a/zlt-uaa/src/main/resources/application.yml b/zlt-uaa/src/main/resources/application.yml index 1b33a10e..b16ef73a 100644 --- a/zlt-uaa/src/main/resources/application.yml +++ b/zlt-uaa/src/main/resources/application.yml @@ -44,4 +44,8 @@ zlt: enabled: false includeSqls: # 应用列表 - - com.central.oauth.mapper.ClientMapper.findList \ No newline at end of file + - com.central.oauth.mapper.ClientMapper.findList +uaa: + wx: + appId: + appsecret: