[feat]:用户微信登录模块

This commit is contained in:
李世琳
2024-12-16 17:00:32 +08:00
parent 6d27d59050
commit 0a99d1c2c8
14 changed files with 279 additions and 16 deletions
@@ -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()));
}
}
@@ -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;
}
@@ -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);
@@ -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
* <p>
* 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<String> paramNames() {
return List.of(OAuth2ParameterNames.CODE);
}
@Override
protected BaseAuthenticationToken getToken(MultiValueMap<String, String> parameters) {
String code = OAuthEndpointUtils.getParam(parameters, OAuth2ParameterNames.CODE);
return new TencentAuthenticationToken(code);
}
}
@@ -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
* <p>
* 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<? extends OAuth2Token> 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<String,Object> 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<String, Object> 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<String, String> params = new HashMap<>();
params.put("appid", "appId");
params.put("secret", "appSecret");
params.put("js_code", code);
params.put("grant_type", "authorization_code");
HttpEntity<Map<String, String>> entity = new HttpEntity<>(params, headers);
ResponseEntity<Map> response = restTemplate.exchange(
"WX_LOGIN_URL",
HttpMethod.POST,
entity,
Map.class
);
if (response.getStatusCode().is2xxSuccessful()) {
Map<String, Object> 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());
}
}
}
+5 -1
View File
@@ -44,4 +44,8 @@ zlt:
enabled: false
includeSqls:
# 应用列表
- com.central.oauth.mapper.ClientMapper.findList
- com.central.oauth.mapper.ClientMapper.findList
uaa:
wx:
appId:
appsecret: