优化代码支持多用户类型扩展
This commit is contained in:
@@ -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<String> responseTypes = authentication.getOAuth2Request().getResponseTypes();
|
||||
Map<String, Object> additionalInfo = new HashMap<>(3);
|
||||
String accountType = AuthUtils.getAccountType(authentication.getUserAuthentication());
|
||||
additionalInfo.put(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME, accountType);
|
||||
|
||||
if (responseTypes.contains(SecurityConstants.ID_TOKEN)
|
||||
|| "authJwt".equals(tokenStoreProperties.getType())) {
|
||||
Map<String, Object> additionalInfo = new HashMap<>(2);
|
||||
Object principal = authentication.getPrincipal();
|
||||
//增加id参数
|
||||
if (principal instanceof SysUser) {
|
||||
@@ -132,8 +136,8 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
|
||||
additionalInfo.put("id", user.getId());
|
||||
}
|
||||
}
|
||||
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
|
||||
}
|
||||
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
|
||||
return accessToken;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,21 +4,24 @@ 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.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
|
||||
@@ -27,6 +30,7 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
|
||||
import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* spring security配置
|
||||
@@ -48,7 +52,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
private AuthenticationEntryPoint authenticationEntryPoint;
|
||||
|
||||
@Resource
|
||||
private UserDetailsService userDetailsService;
|
||||
private UserDetailServiceFactory userDetailsServiceFactory;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
@@ -71,6 +75,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Autowired
|
||||
private TenantProperties tenantProperties;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationDetailsSource<HttpServletRequest, CustomWebAuthenticationDetails> authenticationDetailsSource;
|
||||
|
||||
/**
|
||||
* 这一步的配置是必不可少的,否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
|
||||
* @return 认证管理对象
|
||||
@@ -88,6 +95,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
filter.setFilterProcessesUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL);
|
||||
filter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
|
||||
filter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(SecurityConstants.LOGIN_FAILURE_PAGE));
|
||||
filter.setAuthenticationDetailsSource(authenticationDetailsSource);
|
||||
return filter;
|
||||
}
|
||||
|
||||
@@ -124,7 +132,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
http.formLogin()
|
||||
.loginPage(SecurityConstants.LOGIN_PAGE)
|
||||
.loginProcessingUrl(SecurityConstants.OAUTH_LOGIN_PRO_URL)
|
||||
.successHandler(authenticationSuccessHandler);
|
||||
.successHandler(authenticationSuccessHandler)
|
||||
.authenticationDetailsSource(authenticationDetailsSource);
|
||||
}
|
||||
|
||||
|
||||
@@ -141,8 +150,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
/**
|
||||
* 全局用户信息
|
||||
*/
|
||||
@Autowired
|
||||
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
|
||||
@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);
|
||||
}*/
|
||||
}
|
||||
|
||||
@@ -5,14 +5,14 @@ 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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
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.core.userdetails.UserDetailsByNameServiceWrapper;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.provider.*;
|
||||
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
|
||||
@@ -27,6 +27,7 @@ import org.springframework.security.oauth2.provider.request.DefaultOAuth2Request
|
||||
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;
|
||||
@@ -45,8 +46,8 @@ public class TokenGranterConfig {
|
||||
@Autowired
|
||||
private ClientDetailsService clientDetailsService;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsService userDetailsService;
|
||||
@Resource
|
||||
private UserDetailServiceFactory userDetailsServiceFactory;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
@@ -163,7 +164,7 @@ public class TokenGranterConfig {
|
||||
tokenServices.setReuseRefreshToken(reuseRefreshToken);
|
||||
tokenServices.setClientDetailsService(clientDetailsService);
|
||||
tokenServices.setTokenEnhancer(tokenEnhancer());
|
||||
addUserDetailsService(tokenServices, this.userDetailsService);
|
||||
addUserDetailsService(tokenServices);
|
||||
return tokenServices;
|
||||
}
|
||||
|
||||
@@ -176,10 +177,10 @@ public class TokenGranterConfig {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void addUserDetailsService(DefaultTokenServices tokenServices, UserDetailsService userDetailsService) {
|
||||
if (userDetailsService != null) {
|
||||
private void addUserDetailsService(DefaultTokenServices tokenServices) {
|
||||
if (this.userDetailsServiceFactory != null) {
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(userDetailsService));
|
||||
provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceFactoryWrapper<>(this.userDetailsServiceFactory));
|
||||
tokenServices.setAuthenticationManager(new ProviderManager(Collections.singletonList(provider)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,10 +46,13 @@ public class OauthTokenAspect {
|
||||
String clientId = getClientId(principal);
|
||||
Map<String, String> parameters = (Map<String, String>) args[1];
|
||||
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();
|
||||
Object proceed = joinPoint.proceed(args);
|
||||
if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {
|
||||
/*
|
||||
如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否则授权码模式可以统一改
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package com.central.oauth.mobile;
|
||||
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
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.BadCredentialsException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
@@ -12,10 +12,14 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* <p>
|
||||
* 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());
|
||||
|
||||
+9
-4
@@ -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
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Component
|
||||
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
@Autowired
|
||||
private ZltUserDetailsService userDetailsService;
|
||||
@Resource
|
||||
private UserDetailServiceFactory userDetailsServiceFactory;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
@@ -25,7 +30,7 @@ public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapte
|
||||
public void configure(HttpSecurity http) {
|
||||
//mobile provider
|
||||
MobileAuthenticationProvider provider = new MobileAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
|
||||
provider.setPasswordEncoder(passwordEncoder);
|
||||
http.authenticationProvider(provider);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
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
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Component
|
||||
public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, CustomWebAuthenticationDetails> {
|
||||
@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);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ import java.util.Date;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
+6
-3
@@ -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
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Component
|
||||
public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
@Autowired
|
||||
private SocialUserDetailsService userDetailsService;
|
||||
private UserDetailServiceFactory userDetailsServiceFactory;
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) {
|
||||
//openId provider
|
||||
OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
|
||||
http.authenticationProvider(provider);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
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
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
|
||||
@@ -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<String> scope = request.getScope();
|
||||
OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
|
||||
if (scope != null && !scope.isEmpty()) {
|
||||
Set<String> 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;
|
||||
@@ -142,4 +227,32 @@ public class CustomTokenServices extends DefaultTokenServices {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,10 @@ public class RedisTokensServiceImpl implements ITokensService {
|
||||
tokenVo.setGrantType(request.getGrantType());
|
||||
}
|
||||
|
||||
Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
|
||||
String accountType = (String)additionalInformation.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
|
||||
tokenVo.setAccountType(accountType);
|
||||
|
||||
result.add(tokenVo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户service工厂
|
||||
*
|
||||
* @author zlt
|
||||
* @version 1.0
|
||||
* @date 2021/7/24
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class UserDetailServiceFactory {
|
||||
private static final String ERROR_MSG = "找不到账号类型为 {} 的实现类";
|
||||
|
||||
@Resource
|
||||
private List<ZltUserDetailsService> userDetailsServices;
|
||||
|
||||
public ZltUserDetailsService getService(Authentication authentication) {
|
||||
String accountType = AuthUtils.getAccountType(authentication);
|
||||
return this.getService(accountType);
|
||||
}
|
||||
|
||||
public ZltUserDetailsService getService(String accountType) {
|
||||
if (StrUtil.isEmpty(accountType)) {
|
||||
accountType = SecurityConstants.DEF_ACCOUNT_TYPE;
|
||||
}
|
||||
log.info("UserDetailServiceFactory.getService:{}", accountType);
|
||||
if (CollUtil.isNotEmpty(userDetailsServices)) {
|
||||
for (ZltUserDetailsService userService : userDetailsServices) {
|
||||
if (userService.supports(accountType)) {
|
||||
return userService;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new InternalAuthenticationServiceException(StrUtil.format(ERROR_MSG, accountType));
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,64 @@
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.social.security.SocialUserDetails;
|
||||
import org.springframework.social.security.SocialUserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class UserDetailServiceImpl implements ZltUserDetailsService, SocialUserDetailsService {
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
package com.central.oauth.service.impl;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.social.security.SocialUserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.central.common.model.LoginAppUser;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* <p>
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
+59
@@ -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
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
public class UserDetailsByNameServiceFactoryWrapper <T extends Authentication> implements
|
||||
AuthenticationUserDetailsService<T>, InitializingBean {
|
||||
@Setter
|
||||
private UserDetailServiceFactory userDetailServiceFactory;
|
||||
|
||||
public UserDetailsByNameServiceFactoryWrapper() {
|
||||
|
||||
}
|
||||
|
||||
public UserDetailsByNameServiceFactoryWrapper(final UserDetailServiceFactory userDetailServiceFactory) {
|
||||
Assert.notNull(userDetailServiceFactory, "userDetailServiceFactory cannot be null.");
|
||||
this.userDetailServiceFactory = userDetailServiceFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether all required properties have been set.
|
||||
*
|
||||
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
|
||||
*/
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
Assert.notNull(this.userDetailServiceFactory, "UserDetailServiceFactory must be set");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the UserDetails object from the wrapped UserDetailsService implementation
|
||||
*/
|
||||
@Override
|
||||
public UserDetails loadUserDetails(T authentication) throws UsernameNotFoundException {
|
||||
ZltUserDetailsService userDetailsService;
|
||||
if (authentication instanceof PreAuthenticatedAuthenticationToken) {
|
||||
userDetailsService = this.userDetailServiceFactory.getService((Authentication)authentication.getPrincipal());
|
||||
} else {
|
||||
userDetailsService = this.userDetailServiceFactory.getService(authentication);
|
||||
}
|
||||
return userDetailsService.loadUserByUsername(authentication.getName());
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
package com.central.oauth.tenant;
|
||||
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.common.feign.UserService;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.oauth.service.impl.UserDetailServiceFactory;
|
||||
import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
|
||||
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.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.oauth2.common.util.OAuth2Utils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -29,8 +28,11 @@ import java.util.Map;
|
||||
@Component
|
||||
@Aspect
|
||||
public class OauthAuthorizeAspect {
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
private final UserDetailServiceFactory userDetailsServiceFactory;
|
||||
|
||||
public OauthAuthorizeAspect(UserDetailServiceFactory userDetailsServiceFactory) {
|
||||
this.userDetailsServiceFactory = userDetailsServiceFactory;
|
||||
}
|
||||
|
||||
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(..))")
|
||||
public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
@@ -43,11 +45,14 @@ public class OauthAuthorizeAspect {
|
||||
String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
|
||||
//判断是否不同租户单点登录
|
||||
if (!requestClientId.equals(clientId)) {
|
||||
Object details = tenantToken.getDetails();
|
||||
try {
|
||||
TenantContextHolder.setTenant(requestClientId);
|
||||
//重新查询对应该租户的角色等信息
|
||||
LoginAppUser user = userService.findByUsername(tenantToken.getName());
|
||||
LoginAppUser user = (LoginAppUser)userDetailsServiceFactory.getService(tenantToken)
|
||||
.loadUserByUsername(tenantToken.getName());
|
||||
tenantToken = new TenantUsernamePasswordAuthenticationToken(user, tenantToken.getCredentials(), user.getAuthorities(), requestClientId);
|
||||
tenantToken.setDetails(details);
|
||||
args[3] = tenantToken;
|
||||
} finally {
|
||||
TenantContextHolder.clear();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.central.oauth.tenant;
|
||||
|
||||
import com.central.oauth.password.PasswordAuthenticationProvider;
|
||||
import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
@@ -14,7 +14,7 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
public class TenantAuthenticationProvider extends DaoAuthenticationProvider {
|
||||
public class TenantAuthenticationProvider extends PasswordAuthenticationProvider {
|
||||
@Override
|
||||
protected Authentication createSuccessAuthentication(Object principal,
|
||||
Authentication authentication, UserDetails user) {
|
||||
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
package com.central.oauth.tenant;
|
||||
|
||||
import com.central.oauth.service.ZltUserDetailsService;
|
||||
import com.central.oauth.service.impl.UserDetailServiceFactory;
|
||||
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
@@ -16,19 +16,19 @@ import org.springframework.stereotype.Component;
|
||||
*/
|
||||
@Component
|
||||
public class TenantAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
|
||||
private ZltUserDetailsService userDetailsService;
|
||||
private final UserDetailServiceFactory userDetailsServiceFactory;
|
||||
|
||||
private PasswordEncoder passwordEncoder;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
public TenantAuthenticationSecurityConfig(ZltUserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
|
||||
this.userDetailsService = userDetailsService;
|
||||
public TenantAuthenticationSecurityConfig(UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
|
||||
this.userDetailsServiceFactory = userDetailsServiceFactory;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(HttpSecurity http) {
|
||||
TenantAuthenticationProvider provider = new TenantAuthenticationProvider();
|
||||
provider.setUserDetailsService(userDetailsService);
|
||||
provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
|
||||
provider.setPasswordEncoder(passwordEncoder);
|
||||
http.authenticationProvider(provider);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user