diff --git a/zlt-uaa/src/main/java/com/central/UaaServerApp.java b/zlt-uaa/src/main/java/com/central/UaaServerApp.java
index b3ac5a29..a52b34e4 100644
--- a/zlt-uaa/src/main/java/com/central/UaaServerApp.java
+++ b/zlt-uaa/src/main/java/com/central/UaaServerApp.java
@@ -1,6 +1,7 @@
package com.central;
import com.central.common.lb.annotation.EnableFeignInterceptor;
+import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@@ -10,6 +11,7 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
* @author zlt
*/
@EnableFeignClients
+@MapperScan(basePackages = "com.central.oauth.mapper")
@EnableFeignInterceptor
@EnableDiscoveryClient
//@EnableRedisHttpSession
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
deleted file mode 100644
index e7d68db9..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
+++ /dev/null
@@ -1,178 +0,0 @@
-package com.central.oauth.config;
-
-import cn.hutool.core.util.StrUtil;
-import com.central.common.constant.SecurityConstants;
-import com.central.common.model.SysUser;
-import com.central.oauth.model.Client;
-import com.central.oauth.service.IClientService;
-import com.central.oauth.service.impl.RedisClientDetailsService;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth.utils.OidcIdTokenBuilder;
-import com.central.oauth2.common.constants.IdTokenClaimNames;
-import com.central.oauth2.common.properties.TokenStoreProperties;
-import com.central.oauth2.common.util.AuthUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.AutoConfigureAfter;
-import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.annotation.Order;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
-import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
-import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
-import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
-import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
-import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.TokenGranter;
-import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
-import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-
-import javax.annotation.Resource;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * OAuth2 授权服务器配置
- *
- * @author zlt
- * @date 2018/10/24
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-@EnableAuthorizationServer
-@AutoConfigureAfter(AuthorizationServerEndpointsConfigurer.class)
-public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
- /**
- * 注入authenticationManager 来支持 password grant type
- */
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private TokenStore tokenStore;
-
- @Autowired
- private WebResponseExceptionTranslator webResponseExceptionTranslator;
-
- @Autowired
- private RedisClientDetailsService clientDetailsService;
-
- @Autowired
- private RandomValueAuthorizationCodeServices authorizationCodeServices;
-
- @Autowired
- private TokenGranter tokenGranter;
-
- /**
- * 配置身份认证器,配置认证方式,TokenStore,TokenGranter,OAuth2RequestFactory
- * @param endpoints
- */
- @Override
- public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
- endpoints.tokenStore(tokenStore)
- .authenticationManager(authenticationManager)
- //.userDetailsService(userDetailsServiceFactory.getService(SecurityConstants.DEF_ACCOUNT_TYPE))
- .authorizationCodeServices(authorizationCodeServices)
- .exceptionTranslator(webResponseExceptionTranslator)
- .tokenGranter(tokenGranter);
- }
-
- /**
- * 配置应用名称 应用id
- * 配置OAuth2的客户端相关信息
- * @param clients
- * @throws Exception
- */
- @Override
- public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
- clients.withClientDetails(clientDetailsService);
- clientDetailsService.loadAllClientToCache();
- }
-
- /**
- * 对应于配置AuthorizationServer安全认证的相关信息,创建ClientCredentialsTokenEndpointFilter核心过滤器
- * @param security
- */
- @Override
- public void configure(AuthorizationServerSecurityConfigurer security) {
- security
- .tokenKeyAccess("isAuthenticated()")
- .checkTokenAccess("permitAll()")
- //让/oauth/token支持client_id以及client_secret作登录认证
- .allowFormAuthenticationForClients();
- }
-
- @Bean
- @Order(1)
- public TokenEnhancer tokenEnhancer(@Autowired(required = false) KeyProperties keyProperties
- , IClientService clientService
- , TokenStoreProperties tokenStoreProperties) {
- return (accessToken, authentication) -> {
- Set responseTypes = authentication.getOAuth2Request().getResponseTypes();
- Map additionalInfo = new HashMap<>(3);
- String accountType = AuthUtils.getAccountType(authentication.getUserAuthentication());
- if (StrUtil.isNotEmpty(accountType)) {
- additionalInfo.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
- }
-
- if (responseTypes.contains(SecurityConstants.ID_TOKEN)
- || "authJwt".equals(tokenStoreProperties.getType())) {
- Object principal = authentication.getPrincipal();
- //增加id参数
- if (principal instanceof SysUser) {
- SysUser user = (SysUser)principal;
- if (responseTypes.contains(SecurityConstants.ID_TOKEN)) {
- //生成id_token
- setIdToken(additionalInfo, authentication, keyProperties, clientService, user);
- }
- if ("authJwt".equals(tokenStoreProperties.getType())) {
- additionalInfo.put("id", user.getId());
- }
- }
- }
- ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
- return accessToken;
- };
- }
-
- /**
- * 生成id_token
- * @param additionalInfo 存储token附加信息对象
- * @param authentication 授权对象
- * @param keyProperties 密钥
- * @param clientService 应用service
- */
- private void setIdToken(Map additionalInfo, OAuth2Authentication authentication
- , KeyProperties keyProperties, IClientService clientService, SysUser user) {
- String clientId = authentication.getOAuth2Request().getClientId();
- Client client = clientService.loadClientByClientId(clientId);
- if (client.getSupportIdToken()) {
- String nonce = authentication.getOAuth2Request().getRequestParameters().get(IdTokenClaimNames.NONCE);
- long now = System.currentTimeMillis();
- long expiresAt = System.currentTimeMillis() + client.getIdTokenValiditySeconds() * 1000;
- String idToken = OidcIdTokenBuilder.builder(keyProperties)
- .issuer(SecurityConstants.ISS)
- .issuedAt(now)
- .expiresAt(expiresAt)
- .subject(String.valueOf(user.getId()))
- .name(user.getNickname())
- .loginName(user.getUsername())
- .picture(user.getHeadImgUrl())
- .audience(clientId)
- .nonce(nonce)
- .build();
-
- additionalInfo.put(SecurityConstants.ID_TOKEN, idToken);
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java
deleted file mode 100644
index 359c8475..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package com.central.oauth.config;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.properties.TenantProperties;
-import com.central.oauth.filter.LoginProcessSetTenantFilter;
-import com.central.oauth.handler.OauthLogoutSuccessHandler;
-import com.central.oauth.password.PasswordAuthenticationProvider;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth.tenant.TenantAuthenticationSecurityConfig;
-import com.central.oauth.tenant.TenantUsernamePasswordAuthenticationFilter;
-import com.central.oauth.mobile.MobileAuthenticationSecurityConfig;
-import com.central.oauth.openid.OpenIdAuthenticationSecurityConfig;
-import com.central.common.config.DefaultPasswordConfig;
-import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-import org.springframework.security.config.http.SessionCreationPolicy;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.AuthenticationEntryPoint;
-import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
-import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
-import org.springframework.security.web.authentication.logout.LogoutHandler;
-import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
-
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * spring security配置
- * 在WebSecurityConfigurerAdapter不拦截oauth要开放的资源
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-@Import(DefaultPasswordConfig.class)
-public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Autowired
- private AuthenticationSuccessHandler authenticationSuccessHandler;
-
- @Autowired(required = false)
- private AuthenticationEntryPoint authenticationEntryPoint;
-
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private PasswordEncoder passwordEncoder;
-
- @Resource
- private LogoutHandler logoutHandler;
-
- @Resource
- private LogoutSuccessHandler logoutSuccessHandler;
-
- @Autowired
- private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;
-
- @Autowired
- private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;
-
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Autowired
- private TenantAuthenticationSecurityConfig tenantAuthenticationSecurityConfig;
-
- @Autowired
- private TenantProperties tenantProperties;
-
- @Autowired
- private AuthenticationDetailsSource authenticationDetailsSource;
-
- /**
- * 这一步的配置是必不可少的,否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
- * @return 认证管理对象
- */
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- return super.authenticationManagerBean();
- }
-
- @Bean
- public TenantUsernamePasswordAuthenticationFilter tenantAuthenticationFilter(AuthenticationManager authenticationManager) {
- TenantUsernamePasswordAuthenticationFilter filter = new TenantUsernamePasswordAuthenticationFilter();
- filter.setAuthenticationManager(authenticationManager);
- filter.setFilterProcessesUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL);
- filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
- filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(SecurityConstants.LOGIN_FAILURE_PAGE));
- filter.setAuthenticationDetailsSource(authenticationDetailsSource);
- return filter;
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests()
- .anyRequest()
- //授权服务器关闭basic认证
- .permitAll()
- .and()
- .logout()
- .logoutUrl(SecurityConstants.LOGOUT_URL)
- .logoutSuccessHandler(logoutSuccessHandler)
- .addLogoutHandler(logoutHandler)
- .clearAuthentication(true)
- .and()
- .apply(openIdAuthenticationSecurityConfig)
- .and()
- .apply(mobileAuthenticationSecurityConfig)
- .and()
- .addFilterBefore(new LoginProcessSetTenantFilter(), UsernamePasswordAuthenticationFilter.class)
- .csrf().disable()
- // 解决不允许显示在iframe的问题
- .headers().frameOptions().disable().cacheControl();
-
- if (tenantProperties.getEnable()) {
- //解决不同租户单点登录时角色没变化
- http.formLogin()
- .loginPage(SecurityConstants.LOGIN_PAGE)
- .and()
- .addFilterAt(tenantAuthenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
- .apply(tenantAuthenticationSecurityConfig);
- } else {
- http.formLogin()
- .loginPage(SecurityConstants.LOGIN_PAGE)
- .loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
- .successHandler(authenticationSuccessHandler)
- .authenticationDetailsSource(authenticationDetailsSource);
- }
-
-
- // 基于密码 等模式可以无session,不支持授权码模式
- if (authenticationEntryPoint != null) {
- http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
- http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
- } else {
- // 授权码模式单独处理,需要session的支持,此模式可以支持所有oauth2的认证
- http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
- }
- }
-
- /**
- * 全局用户信息
- */
- @Override
- public void configure(AuthenticationManagerBuilder auth) {
- PasswordAuthenticationProvider provider = new PasswordAuthenticationProvider();
- provider.setPasswordEncoder(passwordEncoder);
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- auth.authenticationProvider(provider);
- }
- /*public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
- }*/
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityHandlerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityHandlerConfig.java
deleted file mode 100644
index 21466313..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityHandlerConfig.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.central.oauth.config;
-
-import com.central.oauth.exception.ValidateCodeException;
-import com.central.oauth.handler.OauthLogoutHandler;
-import com.central.oauth.handler.OauthLogoutSuccessHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.exceptions.*;
-import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
-import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
-import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.logout.LogoutHandler;
-import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-/**
- * 认证错误处理
- *
- * @author zlt
- */
-@Slf4j
-@Configuration
-public class SecurityHandlerConfig {
- @Bean
- public LogoutHandler logoutHandler() {
- return new OauthLogoutHandler();
- }
-
- @Bean
- public LogoutSuccessHandler logoutSuccessHandler() {
- return new OauthLogoutSuccessHandler();
- }
-
- @Bean
- public WebResponseExceptionTranslator webResponseExceptionTranslator() {
- return new DefaultWebResponseExceptionTranslator() {
- private static final String BAD_MSG = "坏的凭证";
- private static final String BAD_MSG_EN = "Bad credentials";
-
- @Override
- public ResponseEntity translate(Exception e) throws Exception {
- OAuth2Exception oAuth2Exception;
- if (e.getMessage() != null
- && (BAD_MSG.equals(e.getMessage()) || BAD_MSG_EN.equals(e.getMessage()))) {
- oAuth2Exception = new InvalidGrantException("用户名或密码错误", e);
- } else if (e instanceof InternalAuthenticationServiceException
- || e instanceof ValidateCodeException) {
- oAuth2Exception = new InvalidGrantException(e.getMessage(), e);
- } else if (e instanceof OAuth2Exception) {
- oAuth2Exception = (OAuth2Exception)e;
- } else {
- oAuth2Exception = new UnsupportedResponseTypeException("服务内部错误", e);
- }
- ResponseEntity response = super.translate(oAuth2Exception);
- ResponseEntity.status(oAuth2Exception.getHttpErrorCode());
- response.getBody().addAdditionalInformation("resp_code", oAuth2Exception.getHttpErrorCode() + "");
- response.getBody().addAdditionalInformation("resp_msg", oAuth2Exception.getMessage());
-
- return response;
- }
- };
- }
-
- /**
- * 登陆成功
- */
- @Bean
- public AuthenticationSuccessHandler loginSuccessHandler() {
- return new SavedRequestAwareAuthenticationSuccessHandler() {
- @Override
- public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
- Authentication authentication) throws IOException, ServletException {
- super.onAuthenticationSuccess(request, response, authentication);
- }
- };
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/TokenGranterConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/TokenGranterConfig.java
deleted file mode 100644
index 067ca3c7..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/config/TokenGranterConfig.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package com.central.oauth.config;
-
-import com.central.oauth.granter.MobilePwdGranter;
-import com.central.oauth.granter.OpenIdGranter;
-import com.central.oauth.granter.PwdImgCodeGranter;
-import com.central.oauth.service.IValidateCodeService;
-import com.central.oauth.service.impl.CustomTokenServices;
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth.service.impl.UserDetailsByNameServiceFactoryWrapper;
-import com.central.oauth2.common.properties.SecurityProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.ProviderManager;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
-import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
-import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
-import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
-import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
-import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
-import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
-import org.springframework.security.oauth2.provider.token.*;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * token授权模式配置类
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Configuration
-public class TokenGranterConfig {
- @Autowired
- private ClientDetailsService clientDetailsService;
-
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private AuthenticationManager authenticationManager;
-
- @Autowired
- private TokenStore tokenStore;
-
- @Autowired(required = false)
- private List tokenEnhancer;
-
- @Autowired
- private IValidateCodeService validateCodeService;
-
- @Autowired
- private RandomValueAuthorizationCodeServices authorizationCodeServices;
-
- private boolean reuseRefreshToken = true;
-
- private AuthorizationServerTokenServices tokenServices;
-
- private TokenGranter tokenGranter;
-
- @Resource
- private SecurityProperties securityProperties;
-
- /**
- * 授权模式
- */
- @Bean
- @ConditionalOnMissingBean
- public TokenGranter tokenGranter(DefaultTokenServices tokenServices) {
- if (tokenGranter == null) {
- tokenGranter = new TokenGranter() {
- private CompositeTokenGranter delegate;
-
- @Override
- public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
- if (delegate == null) {
- delegate = new CompositeTokenGranter(getAllTokenGranters(tokenServices));
- }
- return delegate.grant(grantType, tokenRequest);
- }
- };
- }
- return tokenGranter;
- }
-
- /**
- * 所有授权模式:默认的5种模式 + 自定义的模式
- */
- protected List getAllTokenGranters(DefaultTokenServices tokenServices) {
- AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
- OAuth2RequestFactory requestFactory = requestFactory();
- //获取默认的授权模式
- List tokenGranters = getDefaultTokenGranters(tokenServices, authorizationCodeServices, requestFactory);
- if (authenticationManager != null) {
- // 添加密码加图形验证码模式
- tokenGranters.add(new PwdImgCodeGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory, validateCodeService));
- // 添加openId模式
- tokenGranters.add(new OpenIdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
- // 添加手机号加密码授权模式
- tokenGranters.add(new MobilePwdGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
- }
- return tokenGranters;
- }
-
- /**
- * 默认的授权模式
- */
- private List getDefaultTokenGranters(AuthorizationServerTokenServices tokenServices
- , AuthorizationCodeServices authorizationCodeServices, OAuth2RequestFactory requestFactory) {
- List tokenGranters = new ArrayList<>();
- // 添加授权码模式
- tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory));
- // 添加刷新令牌的模式
- tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsService, requestFactory));
- // 添加隐士授权模式
- tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetailsService, requestFactory));
- // 添加客户端模式
- tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, requestFactory));
- if (authenticationManager != null) {
- // 添加密码模式
- tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, requestFactory));
- }
- return tokenGranters;
- }
-
- private AuthorizationCodeServices authorizationCodeServices() {
- if (authorizationCodeServices == null) {
- authorizationCodeServices = new InMemoryAuthorizationCodeServices();
- }
- return authorizationCodeServices;
- }
-
- private OAuth2RequestFactory requestFactory() {
- return new DefaultOAuth2RequestFactory(clientDetailsService);
- }
-
- @Bean
- @ConditionalOnMissingBean
- protected DefaultTokenServices createDefaultTokenServices() {
- DefaultTokenServices tokenServices = new CustomTokenServices(securityProperties.getAuth());
- tokenServices.setTokenStore(tokenStore);
- tokenServices.setSupportRefreshToken(true);
- tokenServices.setReuseRefreshToken(reuseRefreshToken);
- tokenServices.setClientDetailsService(clientDetailsService);
- tokenServices.setTokenEnhancer(tokenEnhancer());
- addUserDetailsService(tokenServices);
- return tokenServices;
- }
-
- private TokenEnhancer tokenEnhancer() {
- if (tokenEnhancer != null) {
- TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
- tokenEnhancerChain.setTokenEnhancers(tokenEnhancer);
- return tokenEnhancerChain;
- }
- return null;
- }
-
- private void addUserDetailsService(DefaultTokenServices tokenServices) {
- if (this.userDetailsServiceFactory != null) {
- PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
- provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceFactoryWrapper<>(this.userDetailsServiceFactory));
- tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java
index b98efd9a..fd4b21a0 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/config/WebMvcConfig.java
@@ -1,12 +1,14 @@
package com.central.oauth.config;
-import com.central.common.config.DefaultWebMvcConfig;
-import org.springframework.context.annotation.Configuration;
+/*import com.central.common.config.DefaultWebMvcConfig;
+import org.springframework.context.annotation.Configuration;*/
/**
* @author zlt
* @date 2019/8/5
*/
+/*
@Configuration
public class WebMvcConfig extends DefaultWebMvcConfig {
}
+*/
diff --git a/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java b/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java
index 4dd8097a..cc33dad2 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/controller/ClientController.java
@@ -6,8 +6,8 @@ import com.central.oauth.dto.ClientDto;
import com.central.oauth.model.Client;
import com.central.oauth.service.IClientService;
import com.google.common.collect.Maps;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -22,7 +22,7 @@ import java.util.Map;
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
-@Api(tags = "应用")
+@Tag(name = "应用")
@RestController
@RequestMapping("/clients")
public class ClientController {
@@ -30,32 +30,32 @@ public class ClientController {
private IClientService clientService;
@GetMapping("/list")
- @ApiOperation(value = "应用列表")
+ @Operation(summary = "应用列表")
public PageResult list(@RequestParam Map params) {
return clientService.listClient(params, true);
}
@GetMapping("/{id}")
- @ApiOperation(value = "根据id获取应用")
+ @Operation(summary = "根据id获取应用")
public Client get(@PathVariable Long id) {
return clientService.getById(id);
}
@GetMapping("/all")
- @ApiOperation(value = "所有应用")
+ @Operation(summary = "所有应用")
public Result> allClient() {
PageResult page = clientService.listClient(Maps.newHashMap(), false);
return Result.succeed(page.getData());
}
@DeleteMapping("/{id}")
- @ApiOperation(value = "删除应用")
+ @Operation(summary = "删除应用")
public void delete(@PathVariable Long id) {
clientService.delClient(id);
}
@PostMapping("/saveOrUpdate")
- @ApiOperation(value = "保存或者修改应用")
+ @Operation(summary = "保存或者修改应用")
public Result saveOrUpdate(@RequestBody ClientDto clientDto) throws Exception {
return clientService.saveClient(clientDto);
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java b/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java
deleted file mode 100644
index 088d44f3..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/controller/TokensController.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.central.oauth.controller;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.model.PageResult;
-import com.central.common.model.Result;
-import com.central.oauth.model.TokenVo;
-import com.central.oauth.service.ITokensService;
-import com.central.oauth2.common.util.AuthUtils;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.oauth2.provider.ClientDetails;
-import org.springframework.security.oauth2.provider.ClientDetailsService;
-import org.springframework.web.bind.annotation.*;
-
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-/**
- * token管理接口
- *
- * @author zlt
- */
-@Api(tags = "Token管理")
-@Slf4j
-@RestController
-@RequestMapping("/tokens")
-public class TokensController {
- @Resource
- private ITokensService tokensService;
-
- @Resource
- private ClientDetailsService clientDetailsService;
-
- @Resource
- private PasswordEncoder passwordEncoder;
-
- @GetMapping("")
- @ApiOperation(value = "token列表")
- public PageResult list(@RequestParam Map params, String tenantId) {
- return tokensService.listTokens(params, tenantId);
- }
-
- @GetMapping("/key")
- @ApiOperation(value = "获取jwt密钥")
- public Result key(HttpServletRequest request) {
- try {
- String[] clientArr = AuthUtils.extractClient(request);
- ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientArr[0]);
- if (clientDetails == null || !passwordEncoder.matches(clientArr[1], clientDetails.getClientSecret())) {
- throw new BadCredentialsException("应用ID或密码错误");
- }
- } catch (AuthenticationException ae) {
- return Result.failed(ae.getMessage());
- }
- org.springframework.core.io.Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
- try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
- return Result.succeed(br.lines().collect(Collectors.joining("\n")));
- } catch (IOException ioe) {
- log.error("key error", ioe);
- return Result.failed(ioe.getMessage());
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java b/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java
index a85d4726..dd7170ce 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/controller/ValidateCodeController.java
@@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
/**
* 验证码提供
@@ -31,7 +32,7 @@ public class ValidateCodeController {
* @throws Exception
*/
@GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{deviceId}")
- public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws Exception {
+ public void createCode(@PathVariable String deviceId, HttpServletResponse response) throws IOException {
Assert.notNull(deviceId, "机器码不能为空");
// 设置请求头为输出图片类型
CaptchaUtil.setHeader(response);
@@ -54,7 +55,7 @@ public class ValidateCodeController {
*/
@ResponseBody
@GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
- public Result createCode(@PathVariable String mobile) {
+ public Result createCode(@PathVariable String mobile) {
Assert.notNull(mobile, "手机号不能为空");
return validateCodeService.sendSmsCode(mobile);
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/filter/LoginProcessSetTenantFilter.java b/zlt-uaa/src/main/java/com/central/oauth/filter/LoginProcessSetTenantFilter.java
deleted file mode 100644
index da6dad12..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/filter/LoginProcessSetTenantFilter.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package com.central.oauth.filter;
-
-import cn.hutool.core.util.ArrayUtil;
-import com.central.common.constant.SecurityConstants;
-import com.central.common.context.TenantContextHolder;
-import org.springframework.http.HttpMethod;
-import org.springframework.security.web.savedrequest.DefaultSavedRequest;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
-import org.springframework.security.web.util.matcher.RequestMatcher;
-import org.springframework.web.filter.OncePerRequestFilter;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-/**
- * 设置租户id过滤器
- *
- * @author zlt
- * @date 2020/3/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class LoginProcessSetTenantFilter extends OncePerRequestFilter {
- private static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
-
- private RequestMatcher requiresAuthenticationRequestMatcher;
- public LoginProcessSetTenantFilter() {
- requiresAuthenticationRequestMatcher = new AntPathRequestMatcher(SecurityConstants.OAUTH_LOGIN_PRO_URL, HttpMethod.POST.name());
- }
-
- /**
- * 返回true代表不执行过滤器,false代表执行
- */
- @Override
- protected boolean shouldNotFilter(HttpServletRequest request) {
- if (requiresAuthentication(request)) {
- return false;
- }
- return true;
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
- try {
- DefaultSavedRequest savedRequest = (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
- if (savedRequest != null) {
- String[] clientIds = savedRequest.getParameterValues("client_id");
- if (ArrayUtil.isNotEmpty(clientIds)) {
- //保存租户id
- TenantContextHolder.setTenant(clientIds[0]);
- }
- }
- chain.doFilter(request, response);
- } finally {
- TenantContextHolder.clear();
- }
- }
-
- private boolean requiresAuthentication(HttpServletRequest request) {
- return requiresAuthenticationRequestMatcher.matches(request);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/filter/OauthTokenAspect.java b/zlt-uaa/src/main/java/com/central/oauth/filter/OauthTokenAspect.java
deleted file mode 100644
index 822b9c7c..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/filter/OauthTokenAspect.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package com.central.oauth.filter;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.context.TenantContextHolder;
-import com.central.common.model.Result;
-import com.central.oauth.handler.decryptParamHandler.IDecryptParamHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.annotation.Around;
-import org.aspectj.lang.annotation.Aspect;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
-import org.springframework.security.oauth2.common.util.OAuth2Utils;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-import java.security.Principal;
-import java.util.Map;
-
-/**
- * oauth-token拦截器
- * 1. 赋值租户
- * 2. 统一返回token格式
- *
- * @author zlt
- * @date 2020/3/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-@Component
-@Aspect
-public class OauthTokenAspect {
- @Resource
- private IDecryptParamHandler decryptParamHandler;
-
- @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
- public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {
- try {
- Object[] args = joinPoint.getArgs();
- Principal principal = (Principal) args[0];
- if (!(principal instanceof Authentication)) {
- throw new OAuth2Exception(
- "There is no client authentication. Try adding an appropriate authentication filter.");
- }
- String clientId = getClientId(principal);
- Map parameters = (Map) args[1];
- //解密参数
- decryptParamHandler.decryptParams(parameters);
-
- String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
- if (!parameters.containsKey(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME)) {
- parameters.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, SecurityConstants.DEF_ACCOUNT_TYPE);
- }
-
- //保存租户id
- TenantContextHolder.setTenant(clientId);
- Object proceed = joinPoint.proceed(args);
- if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {
- /*
- 如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否则授权码模式可以统一改
- 因为本项目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以这里就不修改授权码模式的token返回值了
- */
- return proceed;
- } else {
- ResponseEntity responseEntity = (ResponseEntity) proceed;
- OAuth2AccessToken body = responseEntity.getBody();
- return ResponseEntity
- .status(HttpStatus.OK)
- .body(Result.succeed(body));
- }
- } finally {
- TenantContextHolder.clear();
- }
- }
-
- private String getClientId(Principal principal) {
- Authentication client = (Authentication) principal;
- if (!client.isAuthenticated()) {
- throw new OAuth2Exception("The client is not authenticated.");
- }
- String clientId = client.getName();
- if (client instanceof OAuth2Authentication) {
- clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
- }
- return clientId;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/granter/MobilePwdGranter.java b/zlt-uaa/src/main/java/com/central/oauth/granter/MobilePwdGranter.java
deleted file mode 100644
index 1f774e0d..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/granter/MobilePwdGranter.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.central.oauth.granter;
-
-import com.central.oauth2.common.token.MobileAuthenticationToken;
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
-import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * openId授权模式
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class MobilePwdGranter extends AbstractTokenGranter {
- private static final String GRANT_TYPE = "mobile_password";
-
- private final AuthenticationManager authenticationManager;
-
- public MobilePwdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
- , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
- super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
- this.authenticationManager = authenticationManager;
- }
-
- @Override
- protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
- Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
- String mobile = parameters.get("mobile");
- String password = parameters.get("password");
- // Protect from downstream leaks of password
- parameters.remove("password");
-
- Authentication userAuth = new MobileAuthenticationToken(mobile, password);
- ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
- userAuth = authenticationManager.authenticate(userAuth);
- if (userAuth == null || !userAuth.isAuthenticated()) {
- throw new InvalidGrantException("Could not authenticate mobile: " + mobile);
- }
-
- OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
- return new OAuth2Authentication(storedOAuth2Request, userAuth);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/granter/OpenIdGranter.java b/zlt-uaa/src/main/java/com/central/oauth/granter/OpenIdGranter.java
deleted file mode 100644
index fc95bce4..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/granter/OpenIdGranter.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.central.oauth.granter;
-
-import com.central.oauth2.common.token.OpenIdAuthenticationToken;
-import org.springframework.security.authentication.*;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
-import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * openId授权模式
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class OpenIdGranter extends AbstractTokenGranter {
- private static final String GRANT_TYPE = "openId";
-
- private final AuthenticationManager authenticationManager;
-
- public OpenIdGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
- , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
- super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
- this.authenticationManager = authenticationManager;
- }
-
- @Override
- protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
- Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
- String openId = parameters.get("openId");
-
- Authentication userAuth = new OpenIdAuthenticationToken(openId);
- ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
- userAuth = authenticationManager.authenticate(userAuth);
- if (userAuth == null || !userAuth.isAuthenticated()) {
- throw new InvalidGrantException("Could not authenticate openId: " + openId);
- }
-
- OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
- return new OAuth2Authentication(storedOAuth2Request, userAuth);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/granter/PwdImgCodeGranter.java b/zlt-uaa/src/main/java/com/central/oauth/granter/PwdImgCodeGranter.java
deleted file mode 100644
index 53d2b0d6..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/granter/PwdImgCodeGranter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.central.oauth.granter;
-
-import com.central.oauth.service.IValidateCodeService;
-import org.springframework.security.authentication.*;
-import org.springframework.security.oauth2.provider.*;
-import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
-import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * password添加图像验证码授权模式
- *
- * @author zlt
- * @date 2020/7/11
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class PwdImgCodeGranter extends ResourceOwnerPasswordTokenGranter {
- private static final String GRANT_TYPE = "password_code";
-
- private final IValidateCodeService validateCodeService;
-
- public PwdImgCodeGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices
- , ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, IValidateCodeService validateCodeService) {
- super(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
- this.validateCodeService = validateCodeService;
- }
-
- @Override
- protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
- Map parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
- String deviceId = parameters.get("deviceId");
- String validCode = parameters.get("validCode");
- //校验图形验证码
- validateCodeService.validate(deviceId, validCode);
-
- return super.getOAuth2Authentication(client, tokenRequest);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java
deleted file mode 100644
index b3a3d49f..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutHandler.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.central.oauth.handler;
-
-import cn.hutool.core.util.StrUtil;
-import com.central.oauth.utils.UsernameHolder;
-import com.central.oauth2.common.properties.SecurityProperties;
-import com.central.oauth2.common.util.AuthUtils;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.common.OAuth2RefreshToken;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-import org.springframework.security.web.authentication.logout.LogoutHandler;
-import org.springframework.util.Assert;
-
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-/**
- * @author zlt
- * @date 2018/10/17
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-public class OauthLogoutHandler implements LogoutHandler {
- @Resource
- private TokenStore tokenStore;
-
- @Resource
- private SecurityProperties securityProperties;
-
- @Override
- public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
- Assert.notNull(tokenStore, "tokenStore must be set");
- String token = request.getParameter("token");
- if (StrUtil.isEmpty(token)) {
- token = AuthUtils.extractToken(request);
- }
- if(StrUtil.isNotEmpty(token)){
- if (securityProperties.getAuth().getUnifiedLogout()) {
- OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
- UsernameHolder.setContext(oAuth2Authentication.getName());
- }
-
- OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
- OAuth2RefreshToken refreshToken;
- if (existingAccessToken != null) {
- if (existingAccessToken.getRefreshToken() != null) {
- log.info("remove refreshToken!", existingAccessToken.getRefreshToken());
- refreshToken = existingAccessToken.getRefreshToken();
- tokenStore.removeRefreshToken(refreshToken);
- }
- log.info("remove existingAccessToken!", existingAccessToken);
- tokenStore.removeAccessToken(existingAccessToken);
- }
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java
deleted file mode 100644
index 78dae8e0..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/OauthLogoutSuccessHandler.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.central.oauth.handler;
-
-import cn.hutool.core.util.StrUtil;
-import com.central.common.model.Result;
-import com.central.common.utils.JsonUtil;
-import com.central.oauth.service.impl.UnifiedLogoutService;
-import com.central.oauth2.common.properties.SecurityProperties;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.web.DefaultRedirectStrategy;
-import org.springframework.security.web.RedirectStrategy;
-import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
-
-import javax.annotation.Resource;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.io.PrintWriter;
-
-/**
- * @author zlt
- * @date 2020/3/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Slf4j
-public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
- private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
-
- @Resource
- private UnifiedLogoutService unifiedLogoutService;
-
- @Resource
- private SecurityProperties securityProperties;
-
- @Override
- public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
- if (securityProperties.getAuth().getUnifiedLogout()) {
- unifiedLogoutService.allLogout();
- }
-
- String redirectUri = request.getParameter("redirect_uri");
- if (StrUtil.isNotEmpty(redirectUri)) {
- //重定向指定的地址
- redirectStrategy.sendRedirect(request, response, redirectUri);
- } else {
- response.setStatus(HttpStatus.OK.value());
- response.setCharacterEncoding("UTF-8");
- response.setContentType(MediaType.APPLICATION_JSON_VALUE);
- PrintWriter writer = response.getWriter();
- String jsonStr = JsonUtil.toJSONString(Result.succeed("登出成功"));
- writer.write(jsonStr);
- writer.flush();
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/IDecryptParamHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/IDecryptParamHandler.java
deleted file mode 100644
index 942f3e1c..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/IDecryptParamHandler.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package com.central.oauth.handler.decryptParamHandler;
-
-import cn.hutool.core.collection.CollUtil;
-import cn.hutool.core.util.StrUtil;
-
-import java.util.Map;
-
-/**
- * 解密参数的处理接口
- *
- * @author zlt
- * @version 1.0
- * @date 2022/12/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public interface IDecryptParamHandler {
- String SEPARATOR = ";";
- /**
- * 需要解密的参数名,多个以 ; 隔离
- * 例如:decrypt_param=username;password
- */
- String PARAM_KEY_DECRYPT_PARAM = "decrypt_param";
-
- /**
- * 根据 parameters里面decrypt_param 的值进行参数解密,并把解密后的值替换原值
- * @param parameters 参数集合
- */
- default void decryptParams(Map parameters) {
- if (CollUtil.isNotEmpty(parameters)) {
- //从 parameters 中获取 decrypt_param 参数值
- String decryptParam = parameters.get(PARAM_KEY_DECRYPT_PARAM);
- //如果参数decrypt_param有值,则进行参数解密
- if (StrUtil.isNotEmpty(decryptParam)) {
- String[] paramNames = decryptParam.split(SEPARATOR);
- this.decrypt(paramNames, parameters);
- }
- }
- }
-
- /**
- * 解密并更新参数值
- * @param paramNames 需要解密的参数名
- * @param parameters 参数集合(参数名:参数值)
- */
- void decrypt(String[] paramNames, Map parameters);
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/RsaDecryptParamHandler.java b/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/RsaDecryptParamHandler.java
deleted file mode 100644
index ea324f5e..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/handler/decryptParamHandler/RsaDecryptParamHandler.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.central.oauth.handler.decryptParamHandler;
-
-import cn.hutool.core.util.StrUtil;
-import cn.hutool.crypto.SecureUtil;
-import cn.hutool.crypto.asymmetric.KeyType;
-import cn.hutool.crypto.asymmetric.RSA;
-import com.central.oauth2.common.properties.AuthProperties;
-import com.central.oauth2.common.properties.SecurityProperties;
-import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
-import org.springframework.stereotype.Service;
-
-import java.util.Map;
-
-/**
- * 使用rsa算法对参数进行解密
- *
- * @author zlt
- * @version 1.0
- * @date 2022/12/29
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Service
-public class RsaDecryptParamHandler implements IDecryptParamHandler {
- private final AuthProperties authProperties;
-
- public RsaDecryptParamHandler(SecurityProperties securityProperties) {
- this.authProperties = securityProperties.getAuth();
- }
-
- @Override
- public void decrypt(String[] paramNames, Map parameters) {
- RSA rsaTools = SecureUtil.rsa(authProperties.getDecryptParamPrivateKey(), null);
- String value;
- for (String param : paramNames) {
- value = parameters.get(param);
- if (StrUtil.isNotEmpty(value)) {
- //解密
- value = this.decrypt(rsaTools, value, param);
- //更新参数为解密后的值
- parameters.put(param, value);
- }
- }
- }
-
- private String decrypt(RSA rsaTools, String value, String param) {
- try {
- return rsaTools.decryptStr(value, KeyType.PrivateKey);
- } catch (Exception e) {
- throw new OAuth2Exception("参数 " + param + " 解密失败!");
- }
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/listener/RedisKeyExpirationListener.java b/zlt-uaa/src/main/java/com/central/oauth/listener/RedisKeyExpirationListener.java
deleted file mode 100644
index eb4e1db7..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/listener/RedisKeyExpirationListener.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package com.central.oauth.listener;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.common.redis.template.RedisRepository;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.data.redis.connection.Message;
-import org.springframework.data.redis.connection.RedisConnection;
-import org.springframework.data.redis.connection.RedisConnectionFactory;
-import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
-import org.springframework.data.redis.listener.RedisMessageListenerContainer;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
-import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
-import org.springframework.stereotype.Component;
-
-/**
- *
- * redis过期key监听器
- * @author zlt
- *
- */
-@Component
-@Slf4j
-public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
- @Autowired
- private RedisRepository redisRepository;
- private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
- private final RedisConnectionFactory connectionFactory;
-
- public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, RedisConnectionFactory connectionFactory) {
- super(listenerContainer);
- this.connectionFactory = connectionFactory;
- }
-
- @Override
- public void onMessage(Message message, byte[] pattern) {
- if (message == null) {
- log.debug("message不能为空");
- return;
- }
- //获取失效的的key
- String expiredKey = message.toString();
- if (StringUtils.isEmpty(expiredKey)) {
- log.debug("expiredKey不能为空");
- return;
- }
- String accesskey = expiredKey.substring(0, expiredKey.indexOf(":") + 1);
- if (!"access:".equals(accesskey)) {
- log.debug("非需要监听key,跳过");
- return;
- }
- String accessValue = expiredKey.substring(expiredKey.indexOf(":") + 1);
- // 分布式集群部署下防止一个过期被多个服务重复消费
- String qc = "qc:" + accessValue;
- String oldLock = redisRepository.getAndSet(qc, "1");
- if (StringUtils.isNotEmpty(oldLock) && "1".equals(oldLock)) {
- log.debug("其他节点已经处理了该数据,跳过");
- return;
- }
- byte[] accessBakKey = serializeKey(SecurityConstants.ACCESS_BAK + accessValue);
- byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + accessValue);
- RedisConnection conn = getConnection();
- try {
- byte[] access = conn.get(accessBakKey);
- byte[] auth = conn.get(authKey);
- OAuth2Authentication authentication = deserializeAuthentication(auth);
- if (authentication != null) {
- byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
- byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
- conn.openPipeline();
- conn.lRem(unameKey, 1, access);
- conn.lRem(clientId, 1, access);
- conn.closePipeline();
- }
- } catch (Exception e) {
- log.error(e.getMessage());
- } finally {
- conn.del(serializeKey(qc));
- conn.close();
- }
-
- }
-
- private byte[] serializeKey(String object) {
- return serialize("" + object);
- }
-
- private byte[] serialize(String string) {
- return serializationStrategy.serialize(string);
- }
-
- private RedisConnection getConnection() {
- return connectionFactory.getConnection();
- }
-
- private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
- return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
- }
-
- private static String getApprovalKey(OAuth2Authentication authentication) {
- String userName = authentication.getUserAuthentication() == null ? ""
- : authentication.getUserAuthentication().getName();
- return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
- }
-
- private static String getApprovalKey(String clientId, String userName) {
- return clientId + (userName == null ? "" : ":" + userName);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationProvider.java
deleted file mode 100644
index 99e5fcde..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationProvider.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.central.oauth.mobile;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth2.common.token.MobileAuthenticationToken;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.crypto.password.PasswordEncoder;
-
-/**
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-public class MobileAuthenticationProvider implements AuthenticationProvider {
- private UserDetailServiceFactory userDetailsServiceFactory;
- private PasswordEncoder passwordEncoder;
-
- @Override
- public Authentication authenticate(Authentication authentication) {
- MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
- String mobile = (String) authenticationToken.getPrincipal();
- String password = (String) authenticationToken.getCredentials();
- UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByMobile(mobile);
- if (user == null) {
- throw new InternalAuthenticationServiceException("手机号或密码错误");
- }
- if (!passwordEncoder.matches(password, user.getPassword())) {
- throw new InternalAuthenticationServiceException("手机号或密码错误");
- }
- MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, password, user.getAuthorities());
- authenticationResult.setDetails(authenticationToken.getDetails());
- return authenticationResult;
- }
-
- @Override
- public boolean supports(Class> authentication) {
- return MobileAuthenticationToken.class.isAssignableFrom(authentication);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java
deleted file mode 100644
index 4aaa7a9a..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.central.oauth.mobile;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.DefaultSecurityFilterChain;
-import org.springframework.stereotype.Component;
-
-import javax.annotation.Resource;
-
-/**
- * mobile的相关处理配置
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter {
- @Resource
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Autowired
- private PasswordEncoder passwordEncoder;
-
- @Override
- public void configure(HttpSecurity http) {
- //mobile provider
- MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- provider.setPasswordEncoder(passwordEncoder);
- http.authenticationProvider(provider);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/model/CustomAuthenticationDetailsSource.java b/zlt-uaa/src/main/java/com/central/oauth/model/CustomAuthenticationDetailsSource.java
deleted file mode 100644
index 77e36ea4..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/model/CustomAuthenticationDetailsSource.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.central.oauth.model;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.stereotype.Component;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-/**
- * 表单登录的认证信息对象
- *
- * @author zlt
- * @version 1.0
- * @date 2021/7/21
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource {
- @Override
- public CustomWebAuthenticationDetails buildDetails(HttpServletRequest context) {
- String remoteAddress = context.getRemoteAddr();
- HttpSession session = context.getSession(false);
- String sessionId = session != null ? session.getId() : null;
- String accountType = context.getParameter(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
- return new CustomWebAuthenticationDetails(remoteAddress, sessionId, accountType);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java
deleted file mode 100644
index 4a4623d8..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.central.oauth.openid;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import com.central.oauth2.common.token.OpenIdAuthenticationToken;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.UserDetails;
-
-/**
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-public class OpenIdAuthenticationProvider implements AuthenticationProvider {
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Override
- public Authentication authenticate(Authentication authentication) {
- OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
- String openId = (String) authenticationToken.getPrincipal();
- UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByUserId(openId);
- if (user == null) {
- throw new InternalAuthenticationServiceException("openId错误");
- }
- OpenIdAuthenticationToken authenticationResult = new OpenIdAuthenticationToken(user, user.getAuthorities());
- authenticationResult.setDetails(authenticationToken.getDetails());
- return authenticationResult;
- }
-
- @Override
- public boolean supports(Class> authentication) {
- return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java
deleted file mode 100644
index f5ef56cb..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.central.oauth.openid;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.web.DefaultSecurityFilterChain;
-import org.springframework.stereotype.Component;
-
-/**
- * openId的相关处理配置
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Component
-public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter {
- @Autowired
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- @Override
- public void configure(HttpSecurity http) {
- //openId provider
- OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
- provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
- http.authenticationProvider(provider);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/password/PasswordAuthenticationProvider.java b/zlt-uaa/src/main/java/com/central/oauth/password/PasswordAuthenticationProvider.java
deleted file mode 100644
index 7fbdd579..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/password/PasswordAuthenticationProvider.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package com.central.oauth.password;
-
-import com.central.oauth.service.impl.UserDetailServiceFactory;
-import lombok.Getter;
-import lombok.Setter;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.authentication.InternalAuthenticationServiceException;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsPasswordService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.security.crypto.factory.PasswordEncoderFactories;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.util.Assert;
-
-/**
- * 扩展用户名密码provider
- *
- * @author zlt
- * @version 1.0
- * @date 2021/7/24
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Setter
-@Getter
-public class PasswordAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
- private UserDetailServiceFactory userDetailsServiceFactory;
-
- private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
-
- private PasswordEncoder passwordEncoder;
-
- /**
- * The password used to perform
- * {@link PasswordEncoder#matches(CharSequence, String)} on when the user is
- * not found to avoid SEC-2056. This is necessary, because some
- * {@link PasswordEncoder} implementations will short circuit if the password is not
- * in a valid format.
- */
- private volatile String userNotFoundEncodedPassword;
-
- private UserDetailsPasswordService userDetailsPasswordService;
-
- public PasswordAuthenticationProvider() {
- setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
- }
-
- // ~ Methods
- // ========================================================================================================
-
- @Override
- @SuppressWarnings("deprecation")
- protected void additionalAuthenticationChecks(UserDetails userDetails,
- UsernamePasswordAuthenticationToken authentication)
- throws AuthenticationException {
- if (authentication.getCredentials() == null) {
- logger.debug("Authentication failed: no credentials provided");
-
- throw new BadCredentialsException(messages.getMessage(
- "AbstractUserDetailsAuthenticationProvider.badCredentials",
- "Bad credentials"));
- }
-
- String presentedPassword = authentication.getCredentials().toString();
-
- if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
- logger.debug("Authentication failed: password does not match stored value");
-
- throw new BadCredentialsException(messages.getMessage(
- "AbstractUserDetailsAuthenticationProvider.badCredentials",
- "Bad credentials"));
- }
- }
-
- @Override
- protected void doAfterPropertiesSet() {
- Assert.notNull(this.userDetailsServiceFactory, "A UserDetailsService must be set");
- }
-
- @Override
- protected final UserDetails retrieveUser(String username,
- UsernamePasswordAuthenticationToken authentication)
- throws AuthenticationException {
- prepareTimingAttackProtection();
- try {
- UserDetails loadedUser = userDetailsServiceFactory.getService(authentication).loadUserByUsername(username);
- if (loadedUser == null) {
- throw new InternalAuthenticationServiceException(
- "UserDetailsService returned null, which is an interface contract violation");
- }
- return loadedUser;
- }
- catch (UsernameNotFoundException ex) {
- mitigateAgainstTimingAttack(authentication);
- throw ex;
- }
- catch (InternalAuthenticationServiceException ex) {
- throw ex;
- }
- catch (Exception ex) {
- throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
- }
- }
-
- @Override
- protected Authentication createSuccessAuthentication(Object principal,
- Authentication authentication, UserDetails user) {
- boolean upgradeEncoding = this.userDetailsPasswordService != null
- && this.passwordEncoder.upgradeEncoding(user.getPassword());
- if (upgradeEncoding) {
- String presentedPassword = authentication.getCredentials().toString();
- String newPassword = this.passwordEncoder.encode(presentedPassword);
- user = this.userDetailsPasswordService.updatePassword(user, newPassword);
- }
- return super.createSuccessAuthentication(principal, authentication, user);
- }
-
- private void prepareTimingAttackProtection() {
- if (this.userNotFoundEncodedPassword == null) {
- this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
- }
- }
-
- private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
- if (authentication.getCredentials() != null) {
- String presentedPassword = authentication.getCredentials().toString();
- this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
- }
- }
-
- /**
- * Sets the PasswordEncoder instance to be used to encode and validate passwords. If
- * not set, the password will be compared using {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}
- *
- * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder}
- * types.
- */
- public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
- Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
- this.passwordEncoder = passwordEncoder;
- this.userNotFoundEncodedPassword = null;
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java b/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java
index eed136a1..490bc0c7 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java
@@ -1,29 +1,29 @@
-package com.central.oauth.service;
-
-import com.central.common.model.PageResult;
-import com.central.common.model.Result;
-import com.central.common.service.ISuperService;
-import com.central.oauth.model.Client;
-
-import java.util.Map;
-
-/**
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public interface IClientService extends ISuperService {
- Result saveClient(Client clientDto) throws Exception;
-
- /**
- * 查询应用列表
- * @param params
- * @param isPage 是否分页
- */
- PageResult listClient(Map params, boolean isPage);
-
- void delClient(long id);
-
- Client loadClientByClientId(String clientId);
-}
+package com.central.oauth.service;
+
+import com.central.common.model.PageResult;
+import com.central.common.model.Result;
+import com.central.common.service.ISuperService;
+import com.central.oauth.model.Client;
+
+import java.util.Map;
+
+/**
+ * @author zlt
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public interface IClientService extends ISuperService {
+ Result saveClient(Client clientDto) throws Exception;
+
+ /**
+ * 查询应用列表
+ * @param params
+ * @param isPage 是否分页
+ */
+ PageResult listClient(Map params, boolean isPage);
+
+ void delClient(long id);
+
+ Client loadClientByClientId(String clientId);
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java b/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java
index 75ee0c6c..e013cf7b 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/IValidateCodeService.java
@@ -1,40 +1,38 @@
-package com.central.oauth.service;
-
-import com.central.common.model.Result;
-
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * @author zlt
- * @date 2018/12/10
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public interface IValidateCodeService {
- /**
- * 保存图形验证码
- * @param deviceId 前端唯一标识
- * @param imageCode 验证码
- */
- void saveImageCode(String deviceId, String imageCode);
-
- Result sendSmsCode(String mobile);
-
- /**
- * 获取验证码
- * @param deviceId 前端唯一标识/手机号
- */
- String getCode(String deviceId);
-
- /**
- * 删除验证码
- * @param deviceId 前端唯一标识/手机号
- */
- void remove(String deviceId);
-
- /**
- * 验证验证码
- */
- void validate(String deviceId, String validCode);
-}
+package com.central.oauth.service;
+
+import com.central.common.model.Result;
+
+/**
+ * @author zlt
+ * @date 2018/12/10
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public interface IValidateCodeService {
+ /**
+ * 保存图形验证码
+ * @param deviceId 前端唯一标识
+ * @param imageCode 验证码
+ */
+ void saveImageCode(String deviceId, String imageCode);
+
+ Result sendSmsCode(String mobile);
+
+ /**
+ * 获取验证码
+ * @param deviceId 前端唯一标识/手机号
+ */
+ String getCode(String deviceId);
+
+ /**
+ * 删除验证码
+ * @param deviceId 前端唯一标识/手机号
+ */
+ void remove(String deviceId);
+
+ /**
+ * 验证验证码
+ */
+ void validate(String deviceId, String validCode);
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomTokenServices.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomTokenServices.java
deleted file mode 100644
index 6ce79c31..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/CustomTokenServices.java
+++ /dev/null
@@ -1,258 +0,0 @@
-package com.central.oauth.service.impl;
-
-import com.central.common.constant.SecurityConstants;
-import com.central.oauth2.common.properties.AuthProperties;
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.oauth2.common.*;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
-import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.OAuth2Request;
-import org.springframework.security.oauth2.provider.TokenRequest;
-import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
-import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-import org.springframework.security.oauth2.provider.token.TokenStore;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.util.Date;
-import java.util.Set;
-import java.util.UUID;
-
-/**
- * 重写 DefaultTokenServices,实现登录同应用同账号互踢
- *
- * @author zlt
- * @date 2021/1/28
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-public class CustomTokenServices extends DefaultTokenServices {
- private TokenStore tokenStore;
- private TokenEnhancer accessTokenEnhancer;
- private AuthenticationManager authenticationManager;
- private boolean supportRefreshToken = false;
- private boolean reuseRefreshToken = true;
-
- /**
- * 是否登录同应用同账号互踢
- */
- private final AuthProperties authProperties;
-
- public CustomTokenServices(AuthProperties auth) {
- this.authProperties = auth;
- }
-
- @Override
- @Transactional
- public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
- OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
- OAuth2RefreshToken refreshToken = null;
- if (existingAccessToken != null) {
- if (authProperties.getIsSingleLogin()) {
- if (existingAccessToken.getRefreshToken() != null) {
- tokenStore.removeRefreshToken(existingAccessToken.getRefreshToken());
- }
- tokenStore.removeAccessToken(existingAccessToken);
- } else if (existingAccessToken.isExpired()) {
- if (existingAccessToken.getRefreshToken() != null) {
- refreshToken = existingAccessToken.getRefreshToken();
- // The token store could remove the refresh token when the
- // access token is removed, but we want to
- // be sure...
- tokenStore.removeRefreshToken(refreshToken);
- }
- tokenStore.removeAccessToken(existingAccessToken);
- } else if (authProperties.getIsShareToken()) {
- // oidc每次授权都刷新id_token
- existingAccessToken = refreshIdToken(existingAccessToken, authentication);
- // Re-store the access token in case the authentication has changed
- tokenStore.storeAccessToken(existingAccessToken, authentication);
- return existingAccessToken;
- }
- }
-
- // Only create a new refresh token if there wasn't an existing one
- // associated with an expired access token.
- // Clients might be holding existing refresh tokens, so we re-use it in
- // the case that the old access token
- // expired.
- if (refreshToken == null) {
- refreshToken = createRefreshToken(authentication);
- }
- // But the refresh token itself might need to be re-issued if it has
- // expired.
- else if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
- ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;
- if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {
- refreshToken = createRefreshToken(authentication);
- }
- }
-
- OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
- tokenStore.storeAccessToken(accessToken, authentication);
- // In case it was modified
- refreshToken = accessToken.getRefreshToken();
- if (refreshToken != null) {
- tokenStore.storeRefreshToken(refreshToken, authentication);
- }
- return accessToken;
-
- }
-
- /**
- * oidc每次授权都刷新id_token
- * @param token 已存在的token
- * @param authentication 认证信息
- */
- private OAuth2AccessToken refreshIdToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
- Set responseTypes = authentication.getOAuth2Request().getResponseTypes();
- if (accessTokenEnhancer != null && responseTypes.contains(SecurityConstants.ID_TOKEN)) {
- return accessTokenEnhancer.enhance(token, authentication);
- }
- return token;
- }
-
- private OAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) {
- if (!isSupportRefreshToken(authentication.getOAuth2Request())) {
- return null;
- }
- int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
- String value = UUID.randomUUID().toString();
- if (validitySeconds > 0) {
- return new DefaultExpiringOAuth2RefreshToken(value, new Date(System.currentTimeMillis()
- + (validitySeconds * 1000L)));
- }
- return new DefaultOAuth2RefreshToken(value);
- }
-
- private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
- DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
- int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
- if (validitySeconds > 0) {
- token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
- }
- token.setRefreshToken(refreshToken);
- token.setScope(authentication.getOAuth2Request().getScope());
-
- return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
- }
-
- @Override
- @Transactional(noRollbackFor={InvalidTokenException.class, InvalidGrantException.class})
- public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest)
- throws AuthenticationException {
- if (!supportRefreshToken) {
- throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
- }
-
- OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
- if (refreshToken == null) {
- throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
- }
-
- OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
- if (this.authenticationManager != null && !authentication.isClientOnly()) {
- AbstractAuthenticationToken userAuthentication = (AbstractAuthenticationToken)authentication.getUserAuthentication();
- Object usesrDetails = userAuthentication.getDetails();
- // The client has already been authenticated, but the user authentication might be old now, so give it a
- // chance to re-authenticate.
- Authentication user = new PreAuthenticatedAuthenticationToken(userAuthentication, "", authentication.getAuthorities());
- user = authenticationManager.authenticate(user);
- //保存账号类型
- ((PreAuthenticatedAuthenticationToken)user).setDetails(usesrDetails);
- Object details = authentication.getDetails();
- authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
- authentication.setDetails(details);
- }
- String clientId = authentication.getOAuth2Request().getClientId();
- if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
- throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
- }
-
- // clear out any access tokens already associated with the refresh
- // token.
- tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
-
- if (isExpired(refreshToken)) {
- tokenStore.removeRefreshToken(refreshToken);
- throw new InvalidTokenException("Invalid refresh token (expired): " + refreshToken);
- }
-
- authentication = createRefreshedAuthentication(authentication, tokenRequest);
- if (!reuseRefreshToken) {
- tokenStore.removeRefreshToken(refreshToken);
- refreshToken = createRefreshToken(authentication);
- }
-
- OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
- tokenStore.storeAccessToken(accessToken, authentication);
- if (!reuseRefreshToken) {
- tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
- }
- return accessToken;
- }
-
- private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) {
- OAuth2Authentication narrowed;
- Set scope = request.getScope();
- OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
- if (scope != null && !scope.isEmpty()) {
- Set originalScope = clientAuth.getScope();
- if (originalScope == null || !originalScope.containsAll(scope)) {
- throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope
- + ".", originalScope);
- }
- else {
- clientAuth = clientAuth.narrowScope(scope);
- }
- }
- narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication());
- return narrowed;
- }
-
- @Override
- public void setTokenStore(TokenStore tokenStore) {
- this.tokenStore = tokenStore;
- super.setTokenStore(tokenStore);
- }
-
- @Override
- public void setTokenEnhancer(TokenEnhancer accessTokenEnhancer) {
- this.accessTokenEnhancer = accessTokenEnhancer;
- super.setTokenEnhancer(accessTokenEnhancer);
- }
-
- @Override
- public void setAuthenticationManager(AuthenticationManager authenticationManager) {
- this.authenticationManager = authenticationManager;
- super.setAuthenticationManager(authenticationManager);
- }
-
- /**
- * Whether to support the refresh token.
- *
- * @param supportRefreshToken Whether to support the refresh token.
- */
- @Override
- public void setSupportRefreshToken(boolean supportRefreshToken) {
- this.supportRefreshToken = supportRefreshToken;
- super.setSupportRefreshToken(supportRefreshToken);
- }
-
- /**
- * Whether to reuse refresh tokens (until expired).
- *
- * @param reuseRefreshToken Whether to reuse refresh tokens (until expired).
- */
- @Override
- public void setReuseRefreshToken(boolean reuseRefreshToken) {
- this.reuseRefreshToken = reuseRefreshToken;
- super.setReuseRefreshToken(reuseRefreshToken);
- }
-}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisAuthorizationCodeServices.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisAuthorizationCodeServices.java
deleted file mode 100644
index 59a2409f..00000000
--- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/RedisAuthorizationCodeServices.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.central.oauth.service.impl;
-
-import com.central.common.redis.template.RedisRepository;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.RedisSerializer;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
-import org.springframework.stereotype.Service;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * JdbcAuthorizationCodeServices替换
- *
- * @author zlt
- *
- * Blog: https://zlt2000.gitee.io
- * Github: https://github.com/zlt2000
- */
-@Service
-public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
- private final RedisRepository redisRepository;
- private final RedisSerializer