diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java similarity index 65% rename from zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java rename to zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java index e579e444..17ede133 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java @@ -1,16 +1,21 @@ -package com.central.oauth2.common.config; +package com.central.oauth2.common; import com.central.oauth2.common.properties.SecurityProperties; import com.central.oauth2.common.properties.TokenStoreProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.ComponentScan; /** + * 鉴权自动配置 + * * @author zlt - * @date 2019/10/7 + * @version 1.0 + * @date 2021/7/24 *
* Blog: https://zlt2000.gitee.io * Github: https://github.com/zlt2000 */ @EnableConfigurationProperties({SecurityProperties.class, TokenStoreProperties.class}) -public class SecurityPropertiesConfig { +@ComponentScan +public class AuthClientAutoConfiguration { } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java index d084e549..1d0b1ec9 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthDbTokenStore.java @@ -3,6 +3,7 @@ package com.central.oauth2.common.store; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; @@ -14,6 +15,7 @@ import javax.sql.DataSource; * @author zlt * @date 2018/7/24 16:23 */ +@Configuration @ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db") public class AuthDbTokenStore { @Autowired diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java index e23b3d41..2d261222 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthJwtTokenStore.java @@ -5,6 +5,7 @@ import com.central.oauth2.common.converter.CustomUserAuthenticationConverter; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 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.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; @@ -28,6 +29,7 @@ import java.util.Map; * Blog: https://zlt2000.gitee.io * Github: https://github.com/zlt2000 */ +@Configuration @ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "authJwt") public class AuthJwtTokenStore { @Resource diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java index 8d5094c3..239dc420 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/AuthRedisTokenStore.java @@ -4,6 +4,7 @@ import com.central.oauth2.common.properties.SecurityProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.security.oauth2.provider.token.TokenStore; @@ -18,6 +19,7 @@ import org.springframework.security.oauth2.provider.token.TokenStore; * Blog: https://zlt2000.gitee.io * Github: https://github.com/zlt2000 */ +@Configuration @ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true) public class AuthRedisTokenStore { @Bean diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java index 606fbb68..c7655696 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/store/ResJwtTokenStore.java @@ -7,6 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; @@ -31,6 +32,7 @@ import java.util.stream.Collectors; * @author zlt * @date 2018/8/20 9:25 */ +@Configuration @ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt") public class ResJwtTokenStore { @Autowired diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomWebAuthenticationDetails.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomWebAuthenticationDetails.java new file mode 100644 index 00000000..95dd1c18 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomWebAuthenticationDetails.java @@ -0,0 +1,37 @@ +package com.central.oauth2.common.token; + +import lombok.Getter; + +import java.io.Serializable; + +/** + * 表单登录的认证信息对象 + * + * @author zlt + * @version 1.0 + * @date 2021/7/24 + *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Getter
+public class CustomWebAuthenticationDetails implements Serializable {
+ private static final long serialVersionUID = - 1;
+
+ private final String accountType;
+ private final String remoteAddress;
+ private final String sessionId;
+
+ public CustomWebAuthenticationDetails(String remoteAddress, String sessionId, String accountType) {
+ this.remoteAddress = remoteAddress;
+ this.sessionId = sessionId;
+ this.accountType = accountType;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(super.toString()).append("; accountType: ").append(this.getAccountType());
+ return sb.toString();
+ }
+}
diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java
index bad4669f..4b717617 100644
--- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java
+++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java
@@ -1,17 +1,19 @@
package com.central.oauth2.common.util;
import com.central.common.constant.CommonConstant;
+import com.central.common.constant.SecurityConstants;
import com.central.common.model.SysUser;
+import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Enumeration;
+import java.util.Map;
/**
* 认证授权相关工具类
@@ -104,4 +106,22 @@ public class AuthUtils {
}
return username;
}
+
+ /**
+ * 获取登陆的帐户类型
+ */
+ public static String getAccountType(Authentication authentication) {
+ Object details = authentication.getDetails();
+ String accountType = null;
+ if (details instanceof CustomWebAuthenticationDetails) {
+ CustomWebAuthenticationDetails detailsObj = (CustomWebAuthenticationDetails) details;
+ accountType = detailsObj.getAccountType();
+ } else {
+ Map
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
public interface SecurityConstants {
/**
@@ -31,6 +34,11 @@ public interface SecurityConstants {
*/
String TENANT_HEADER = "x-tenant-header";
+ /**
+ * 账号类型信息头
+ */
+ String ACCOUNT_TYPE_HEADER = "x-account-type-header";
+
/**
* 基础角色
*/
@@ -167,4 +175,14 @@ public interface SecurityConstants {
* 令牌颁发者
*/
String ISS = "http://zlt2000.cn";
+
+ /**
+ * 默认账号类型
+ */
+ String DEF_ACCOUNT_TYPE = "admin";
+
+ /**
+ * 账号类型参数名
+ */
+ String ACCOUNT_TYPE_PARAM_NAME = "account_type";
}
diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java
index 19a1183f..32e5ef37 100644
--- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java
+++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java
@@ -23,6 +23,9 @@ import java.util.List;
*
* @author zlt
* @date 2018/12/21
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
@@ -61,6 +64,8 @@ public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
String userId = request.getHeader(SecurityConstants.USER_ID_HEADER);
String username = request.getHeader(SecurityConstants.USER_HEADER);
String roles = request.getHeader(SecurityConstants.ROLE_HEADER);
+ //账号类型
+ String accountType = request.getHeader(SecurityConstants.ACCOUNT_TYPE_HEADER);
if (StrUtil.isBlank(username)) {
log.warn("resolveArgument error username is empty");
return null;
diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java
index dd637076..8a02c897 100644
--- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java
+++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java
@@ -3,6 +3,7 @@ package com.central.gateway.auth;
import cn.hutool.core.collection.CollectionUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.SysUser;
+import com.central.oauth2.common.util.AuthUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
@@ -37,12 +38,12 @@ public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHand
String clientId = oauth2Authentication.getOAuth2Request().getClientId();
headerValues.add(SecurityConstants.TENANT_HEADER, clientId);
headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
+ String accountType = AuthUtils.getAccountType(oauth2Authentication.getUserAuthentication());
+ headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, accountType);
ServerWebExchange exchange = webFilterExchange.getExchange();
ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
- .headers(h -> {
- h.addAll(headerValues);
- })
+ .headers(h -> h.addAll(headerValues))
.build();
ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
diff --git a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/UserInfoHeaderFilter.java b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/UserInfoHeaderFilter.java
index ae832a0d..bee07e26 100644
--- a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/UserInfoHeaderFilter.java
+++ b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/UserInfoHeaderFilter.java
@@ -3,6 +3,7 @@ package com.central.gateway.filter.pre;
import cn.hutool.core.collection.CollectionUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.SysUser;
+import com.central.oauth2.common.util.AuthUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
@@ -19,6 +20,9 @@ import static org.springframework.cloud.netflix.zuul.filters.support.FilterConst
*
* @author zlt
* @date 2018/11/20
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
@Component
public class UserInfoHeaderFilter extends ZuulFilter {
@@ -53,6 +57,8 @@ public class UserInfoHeaderFilter extends ZuulFilter {
String clientId = oauth2Authentication.getOAuth2Request().getClientId();
ctx.addZuulRequestHeader(SecurityConstants.TENANT_HEADER, clientId);
ctx.addZuulRequestHeader(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
+ String accountType = AuthUtils.getAccountType(oauth2Authentication.getUserAuthentication());
+ ctx.addZuulRequestHeader(SecurityConstants.ACCOUNT_TYPE_HEADER, accountType);
}
return null;
}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
index d9f8c2a6..85dd7950 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/config/AuthorizationServerConfig.java
@@ -5,9 +5,11 @@ 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;
@@ -15,7 +17,6 @@ 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.core.userdetails.UserDetailsService;
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;
@@ -54,7 +55,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
private AuthenticationManager authenticationManager;
@Resource
- private UserDetailsService userDetailsService;
+ private UserDetailServiceFactory userDetailsServiceFactory;
@Autowired
private TokenStore tokenStore;
@@ -79,7 +80,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
- .userDetailsService(userDetailsService)
+ //.userDetailsService(userDetailsServiceFactory.getService(SecurityConstants.DEF_ACCOUNT_TYPE))
.authorizationCodeServices(authorizationCodeServices)
.exceptionTranslator(webResponseExceptionTranslator)
.tokenGranter(tokenGranter);
@@ -117,9 +118,12 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
, TokenStoreProperties tokenStoreProperties) {
return (accessToken, authentication) -> {
Set
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
@Setter
+@Getter
public class MobileAuthenticationProvider implements AuthenticationProvider {
- private ZltUserDetailsService userDetailsService;
+ private UserDetailServiceFactory userDetailsServiceFactory;
private PasswordEncoder passwordEncoder;
@Override
@@ -23,12 +27,12 @@ public class MobileAuthenticationProvider implements AuthenticationProvider {
MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
String mobile = (String) authenticationToken.getPrincipal();
String password = (String) authenticationToken.getCredentials();
- UserDetails user = userDetailsService.loadUserByMobile(mobile);
+ UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByMobile(mobile);
if (user == null) {
throw new InternalAuthenticationServiceException("手机号或密码错误");
}
if (!passwordEncoder.matches(password, user.getPassword())) {
- throw new BadCredentialsException("手机号或密码错误");
+ throw new InternalAuthenticationServiceException("手机号或密码错误");
}
MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, password, user.getAuthorities());
authenticationResult.setDetails(authenticationToken.getDetails());
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
index 12d09abc..4aaa7a9a 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/mobile/MobileAuthenticationSecurityConfig.java
@@ -1,6 +1,6 @@
package com.central.oauth.mobile;
-import com.central.oauth.service.ZltUserDetailsService;
+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;
@@ -8,15 +8,20 @@ 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
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Component
+public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
@Setter
@Getter
@@ -33,4 +36,8 @@ public class TokenVo implements Serializable {
* 授权类型
*/
private String grantType;
+ /**
+ * 账号类型
+ */
+ private String 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
index 759124ba..4a4623d8 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationProvider.java
@@ -1,24 +1,30 @@
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;
-import org.springframework.social.security.SocialUserDetailsService;
/**
* @author zlt
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
+@Setter
+@Getter
public class OpenIdAuthenticationProvider implements AuthenticationProvider {
-
- private SocialUserDetailsService userDetailsService;
+ private UserDetailServiceFactory userDetailsServiceFactory;
@Override
public Authentication authenticate(Authentication authentication) {
OpenIdAuthenticationToken authenticationToken = (OpenIdAuthenticationToken) authentication;
String openId = (String) authenticationToken.getPrincipal();
- UserDetails user = userDetailsService.loadUserByUserId(openId);
+ UserDetails user = userDetailsServiceFactory.getService(authenticationToken).loadUserByUserId(openId);
if (user == null) {
throw new InternalAuthenticationServiceException("openId错误");
}
@@ -31,12 +37,4 @@ public class OpenIdAuthenticationProvider implements AuthenticationProvider {
public boolean supports(Class> authentication) {
return OpenIdAuthenticationToken.class.isAssignableFrom(authentication);
}
-
- public SocialUserDetailsService getUserDetailsService() {
- return userDetailsService;
- }
-
- public void setUserDetailsService(SocialUserDetailsService userDetailsService) {
- this.userDetailsService = userDetailsService;
- }
}
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
index 2a63c0b2..f5ef56cb 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/openid/OpenIdAuthenticationSecurityConfig.java
@@ -1,27 +1,30 @@
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.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;
/**
* openId的相关处理配置
*
* @author zlt
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
*/
@Component
public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter
+ * 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/ZltUserDetailsService.java b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java
index 5fbb2942..c02809d1 100644
--- a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java
@@ -1,19 +1,35 @@
-package com.central.oauth.service;
-
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-
-/**
- * @author zlt
- * @date 2018/12/28
- */
-public interface ZltUserDetailsService extends UserDetailsService {
- /**
- * 根据电话号码查询用户
- *
- * @param mobile
- * @return
- */
- UserDetails loadUserByMobile(String mobile);
-}
+package com.central.oauth.service;
+
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.social.security.SocialUserDetails;
+
+/**
+ * @author zlt
+ * @date 2018/12/28
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public interface ZltUserDetailsService extends UserDetailsService {
+ /**
+ * 判断实现类是否属于该类型
+ * @param accountType 账号类型
+ */
+ boolean supports(String accountType);
+
+ /**
+ * 根据电话号码查询用户
+ *
+ * @param mobile
+ * @return
+ */
+ UserDetails loadUserByMobile(String mobile);
+
+ /**
+ * 根据用户id/openId查询用户
+ * @param userId 用户id/openId
+ */
+ SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException;
+}
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
index 4f9f46ee..66e1c624 100644
--- 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
@@ -1,12 +1,21 @@
package com.central.oauth.service.impl;
import com.central.common.constant.SecurityConstants;
+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;
@@ -25,6 +34,9 @@ import java.util.UUID;
public class CustomTokenServices extends DefaultTokenServices {
private TokenStore tokenStore;
private TokenEnhancer accessTokenEnhancer;
+ private AuthenticationManager authenticationManager;
+ private boolean supportRefreshToken = false;
+ private boolean reuseRefreshToken = true;
/**
* 是否登录同应用同账号互踢
@@ -131,6 +143,79 @@ public class CustomTokenServices extends DefaultTokenServices {
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
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Slf4j
+@Service
+public class UserDetailServiceFactory {
+ private static final String ERROR_MSG = "找不到账号类型为 {} 的实现类";
+
+ @Resource
+ private List
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+@Slf4j
+@Service
+public class UserDetailServiceImpl implements ZltUserDetailsService {
+ private static final String ACCOUNT_TYPE = SecurityConstants.DEF_ACCOUNT_TYPE;
+
+ @Resource
+ private UserService userService;
+
+ @Override
+ public boolean supports(String accountType) {
+ return ACCOUNT_TYPE.equals(accountType);
+ }
+
+ @Override
+ public UserDetails loadUserByUsername(String username) {
+ LoginAppUser loginAppUser = userService.findByUsername(username);
+ if (loginAppUser == null) {
+ throw new InternalAuthenticationServiceException("用户名或密码错误");
+ }
+ return checkUser(loginAppUser);
+ }
+
+ @Override
+ public SocialUserDetails loadUserByUserId(String openId) {
+ LoginAppUser loginAppUser = userService.findByOpenId(openId);
+ return checkUser(loginAppUser);
+ }
+
+ @Override
+ public UserDetails loadUserByMobile(String mobile) {
+ LoginAppUser loginAppUser = userService.findByMobile(mobile);
+ return checkUser(loginAppUser);
+ }
+
+ private LoginAppUser checkUser(LoginAppUser loginAppUser) {
+ if (loginAppUser != null && !loginAppUser.isEnabled()) {
+ throw new DisabledException("用户已作废");
+ }
+ return loginAppUser;
+ }
+}
diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailsByNameServiceFactoryWrapper.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailsByNameServiceFactoryWrapper.java
new file mode 100644
index 00000000..39f02f2b
--- /dev/null
+++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailsByNameServiceFactoryWrapper.java
@@ -0,0 +1,59 @@
+package com.central.oauth.service.impl;
+
+import com.central.oauth.service.ZltUserDetailsService;
+import lombok.Setter;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.userdetails.*;
+import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
+import org.springframework.util.Assert;
+
+/**
+ * 重写 UserDetailsByNameServiceWrapper 支持多帐户类型
+ *
+ * @author zlt
+ * @version 1.0
+ * @date 2021/7/24
+ * @see UserDetailsByNameServiceWrapper
+ *
+ * Blog: https://zlt2000.gitee.io
+ * Github: https://github.com/zlt2000
+ */
+public class UserDetailsByNameServiceFactoryWrapper