feat: 升级SpringBoot和SpringCloud版本

This commit is contained in:
zlt2000
2023-11-10 14:59:27 +08:00
parent c7dfbc9e39
commit ec616bc1b5
133 changed files with 639 additions and 3666 deletions
@@ -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
@@ -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
* <p>
* 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<String> responseTypes = authentication.getOAuth2Request().getResponseTypes();
Map<String, Object> 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<String, Object> 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);
}
}
}
@@ -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
* <p>
* 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<HttpServletRequest, CustomWebAuthenticationDetails> 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);
}*/
}
@@ -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<OAuth2Exception> 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<OAuth2Exception> 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);
}
};
}
}
@@ -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
* <p>
* 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> 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<TokenGranter> getAllTokenGranters(DefaultTokenServices tokenServices) {
AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
OAuth2RequestFactory requestFactory = requestFactory();
//获取默认的授权模式
List<TokenGranter> 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<TokenGranter> getDefaultTokenGranters(AuthorizationServerTokenServices tokenServices
, AuthorizationCodeServices authorizationCodeServices, OAuth2RequestFactory requestFactory) {
List<TokenGranter> 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)));
}
}
}
@@ -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 {
}
*/
@@ -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<Client> list(@RequestParam Map<String, Object> 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<List<Client>> allClient() {
PageResult<Client> 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);
}
@@ -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<TokenVo> list(@RequestParam Map<String, Object> params, String tenantId) {
return tokensService.listTokens(params, tenantId);
}
@GetMapping("/key")
@ApiOperation(value = "获取jwt密钥")
public Result<String> 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());
}
}
}
@@ -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<String> createCode(@PathVariable String mobile) {
Assert.notNull(mobile, "手机号不能为空");
return validateCodeService.sendSmsCode(mobile);
}
@@ -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
* <p>
* 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);
}
}
@@ -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
* <p>
* 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<String, String> parameters = (Map<String, String>) 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<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) 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;
}
}
@@ -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
* <p>
* 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<String, String> 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);
}
}
@@ -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
* <p>
* 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<String, String> 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);
}
}
@@ -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
* <p>
* 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<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
String deviceId = parameters.get("deviceId");
String validCode = parameters.get("validCode");
//校验图形验证码
validateCodeService.validate(deviceId, validCode);
return super.getOAuth2Authentication(client, tokenRequest);
}
}
@@ -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
* <p>
* 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);
}
}
}
}
@@ -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
* <p>
* 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();
}
}
}
@@ -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
* <p>
* 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<String, String> 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<String, String> parameters);
}
@@ -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
* <p>
* 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<String, String> 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 + " 解密失败!");
}
}
}
@@ -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);
}
}
@@ -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
* <p>
* 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);
}
}
@@ -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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@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);
}
}
@@ -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
* <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);
}
}
@@ -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
* <p>
* 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);
}
}
@@ -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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@Autowired
private UserDetailServiceFactory userDetailsServiceFactory;
@Override
public void configure(HttpSecurity http) {
//openId provider
OpenIdAuthenticationProvider provider = new OpenIdAuthenticationProvider();
provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
http.authenticationProvider(provider);
}
}
@@ -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
* <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,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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface IClientService extends ISuperService<Client> {
Result saveClient(Client clientDto) throws Exception;
/**
* 查询应用列表
* @param params
* @param isPage 是否分页
*/
PageResult<Client> listClient(Map<String, Object> 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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public interface IClientService extends ISuperService<Client> {
Result saveClient(Client clientDto) throws Exception;
/**
* 查询应用列表
* @param params
* @param isPage 是否分页
*/
PageResult<Client> listClient(Map<String, Object> params, boolean isPage);
void delClient(long id);
Client loadClientByClientId(String clientId);
}
@@ -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
* <p>
* 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
* <p>
* 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);
}
@@ -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
* <p>
* 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<String> 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<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;
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);
}
}
@@ -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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
private final RedisRepository redisRepository;
private final RedisSerializer<Object> valueSerializer;
public RedisAuthorizationCodeServices(RedisRepository redisRepository) {
this.redisRepository = redisRepository;
this.valueSerializer = RedisSerializer.java();
}
/**
* 替换JdbcAuthorizationCodeServices的存储策略
* 将存储code到redis,并设置过期时间,10分钟
*/
@Override
protected void store(String code, OAuth2Authentication authentication) {
redisRepository.setExpire(redisKey(code), authentication, 10, TimeUnit.MINUTES, valueSerializer);
}
@Override
protected OAuth2Authentication remove(final String code) {
String codeKey = redisKey(code);
OAuth2Authentication token = (OAuth2Authentication) redisRepository.get(codeKey, valueSerializer);
redisRepository.del(codeKey);
return token;
}
/**
* redis中 code key的前缀
*
* @param code
* @return
*/
private String redisKey(String code) {
return "oauth:code:" + code;
}
}
@@ -1,110 +0,0 @@
package com.central.oauth.service.impl;
import com.central.common.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.util.List;
/**
* @author zlt
* @version 创建时间:2017年11月12日 上午22:57:51
* 类说明
* 将oauth_client_details表数据缓存到redis,这里做个缓存优化
* layui模块中有对oauth_client_details的crud, 注意同步redis的数据
* 注意对oauth_client_details清楚redis db部分数据的清空
*/
@Slf4j
@Service
public class RedisClientDetailsService extends JdbcClientDetailsService {
private RedisTemplate<String, Object> redisTemplate;
public RedisClientDetailsService(DataSource dataSource, RedisTemplate<String, Object> redisTemplate) {
super(dataSource);
this.redisTemplate = redisTemplate;
}
@Override
public ClientDetails loadClientByClientId(String clientId) {
// 先从redis获取
ClientDetails clientDetails = (ClientDetails) redisTemplate.opsForValue().get(clientRedisKey(clientId));
if (clientDetails == null) {
clientDetails = cacheAndGetClient(clientId);
}
return clientDetails;
}
/**
* 缓存client并返回client
* @param clientId
* @return
*/
private ClientDetails cacheAndGetClient(String clientId) {
// 从数据库读取
ClientDetails clientDetails = null;
try {
clientDetails = super.loadClientByClientId(clientId);
if (clientDetails != null) {
// 写入redis缓存
redisTemplate.opsForValue().set(clientRedisKey(clientId), clientDetails);
log.info("缓存clientId:{},{}", clientId, clientDetails);
}
} catch (NoSuchClientException e) {
log.error("clientId:{},{}", clientId, clientId);
} catch (InvalidClientException e) {
log.error("cacheAndGetClient-invalidClient:{}", clientId, e);
}
return clientDetails;
}
@Override
public void updateClientDetails(ClientDetails clientDetails) {
super.updateClientDetails(clientDetails);
cacheAndGetClient(clientDetails.getClientId());
}
@Override
public void updateClientSecret(String clientId, String secret) {
super.updateClientSecret(clientId, secret);
cacheAndGetClient(clientId);
}
@Override
public void removeClientDetails(String clientId) {
super.removeClientDetails(clientId);
removeRedisCache(clientId);
}
/**
* 删除redis缓存
*
* @param clientId
*/
private void removeRedisCache(String clientId) {
redisTemplate.delete(clientRedisKey(clientId));
}
/**
* 将oauth_client_details全表刷入redis
*/
public void loadAllClientToCache() {
List<ClientDetails> list = super.listClientDetails();
if (CollectionUtils.isEmpty(list)) {
log.error("oauth_client_details表数据为空,请检查");
return;
}
list.forEach(client -> redisTemplate.opsForValue().set(clientRedisKey(client.getClientId()), client));
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
}
@@ -1,91 +0,0 @@
package com.central.oauth.service.impl;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.PageResult;
import com.central.common.redis.template.RedisRepository;
import com.central.oauth.model.TokenVo;
import com.central.oauth.service.ITokensService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* token管理服务(redis token)
*
* @author zlt
* @date 2019/7/12
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
public class RedisTokensServiceImpl implements ITokensService {
@Autowired
private RedisRepository redisRepository;
@Override
public PageResult<TokenVo> listTokens(Map<String, Object> params, String clientId) {
Integer page = MapUtils.getInteger(params, "page");
Integer limit = MapUtils.getInteger(params, "limit");
int[] startEnds = PageUtil.transToStartEnd(page-1, limit);
//根据请求参数生成redis的key
String redisKey = getRedisKey(params, clientId);
long size = redisRepository.length(redisKey);
List<TokenVo> result = new ArrayList<>(limit);
RedisSerializer<Object> valueSerializer = RedisSerializer.java();
//查询token集合
List<Object> tokenObjs = redisRepository.getList(redisKey, startEnds[0], startEnds[1]-1, valueSerializer);
if (tokenObjs != null) {
for (Object obj : tokenObjs) {
DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken)obj;
//构造token对象
TokenVo tokenVo = new TokenVo();
tokenVo.setTokenValue(accessToken.getValue());
tokenVo.setExpiration(accessToken.getExpiration());
//获取用户信息
Object authObj = redisRepository.get(SecurityConstants.REDIS_TOKEN_AUTH + accessToken.getValue(), valueSerializer);
OAuth2Authentication authentication = (OAuth2Authentication)authObj;
if (authentication != null) {
OAuth2Request request = authentication.getOAuth2Request();
tokenVo.setUsername(authentication.getName());
tokenVo.setClientId(request.getClientId());
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);
}
}
return PageResult.<TokenVo>builder().data(result).code(0).count(size).build();
}
/**
* 根据请求参数生成redis的key
*/
private String getRedisKey(Map<String, Object> params, String clientId) {
String result;
String username = MapUtils.getString(params, "username");
if (StrUtil.isNotEmpty(username)) {
result = SecurityConstants.REDIS_UNAME_TO_ACCESS + clientId + ":" + username;
} else {
result = SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId;
}
return result;
}
}
@@ -1,112 +0,0 @@
package com.central.oauth.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.central.oauth.utils.UsernameHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.*;
/**
* 统一登出服务
*
* @author zlt
* @version 1.0
* @date 2021/10/21
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Service
public class UnifiedLogoutService {
private final static String LOGOUT_NOTIFY_URL_KEY = "LOGOUT_NOTIFY_URL_LIST";
@Resource
private RestTemplate restTemplate;
@Resource
private TaskExecutor taskExecutor;
@Resource
private RedisClientDetailsService redisClientDetailsService;
@Resource
private TokenStore tokenStore;
@Lazy
@Resource
private DefaultTokenServices tokenServices;
public void allLogout() {
Set<String> urls = this.getLogoutNotifyUrl();
for (String url : urls) {
taskExecutor.execute(() -> {
try {
restTemplate.getForObject(url, Void.class);
} catch (Exception e) {
log.warn(e.getMessage());
}
});
}
}
/**
* 获取登出需要通知的地址集合
*/
private Set<String> getLogoutNotifyUrl() {
String username = UsernameHolder.getContext();
Set<String> logoutNotifyUrls = new HashSet<>();
try {
List<ClientDetails> clientDetails = redisClientDetailsService.listClientDetails();
Map<String, Object> informationMap;
for (ClientDetails client : clientDetails) {
informationMap = client.getAdditionalInformation();
String urls = (String)informationMap.get(LOGOUT_NOTIFY_URL_KEY);
if (StrUtil.isNotEmpty(urls)) {
Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientIdAndUserName(client.getClientId(), username);
if (CollUtil.isNotEmpty(tokens)) {
//注销所有该用户名下的token
tokens.forEach(t -> tokenServices.revokeToken(t.getValue()));
String tokenStr = getTokenValueStr(tokens);
logoutNotifyUrls.addAll(generateNotifyUrls(urls.split(","), tokenStr));
}
}
}
} finally {
UsernameHolder.clearContext();
}
return logoutNotifyUrls;
}
private String getTokenValueStr(Collection<OAuth2AccessToken> tokens) {
if (CollUtil.isNotEmpty(tokens)) {
return StrUtil.join( ",", tokens);
}
return null;
}
private Set<String> generateNotifyUrls(String[] urls, String tokenStr) {
Set<String> urlSet = new HashSet(urls.length);
for (String url : urls) {
StringBuilder urlBuilder = new StringBuilder(url);
if (url.contains("?")) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
}
urlBuilder.append("tokens=").append(tokenStr);
urlSet.add(urlBuilder.toString());
}
return urlSet;
}
}
@@ -1,53 +0,0 @@
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,59 +0,0 @@
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,64 +0,0 @@
package com.central.oauth.tenant;
import com.central.common.context.TenantContextHolder;
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.security.oauth2.common.util.OAuth2Utils;
import org.springframework.stereotype.Component;
import java.security.Principal;
import java.util.Map;
/**
* /oauth/authorize拦截器
* 解决不同租户单点登录时角色没变化
*
* @author zlt
* @date 2020/6/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@Component
@Aspect
public class OauthAuthorizeAspect {
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 {
Object[] args = joinPoint.getArgs();
Map<String, String> parameters = (Map<String, String>) args[1];
Principal principal = (Principal) args[3];
if (principal instanceof TenantUsernamePasswordAuthenticationToken) {
TenantUsernamePasswordAuthenticationToken tenantToken = (TenantUsernamePasswordAuthenticationToken)principal;
String clientId = tenantToken.getClientId();
String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
//判断是否不同租户单点登录
if (!requestClientId.equals(clientId)) {
Object details = tenantToken.getDetails();
try {
TenantContextHolder.setTenant(requestClientId);
//重新查询对应该租户的角色等信息
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();
}
}
}
return joinPoint.proceed(args);
}
}
@@ -1,32 +0,0 @@
package com.central.oauth.tenant;
import com.central.oauth.password.PasswordAuthenticationProvider;
import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
/**
* 增加租户id,解决不同租户单点登录时角色没变化
*
* @author zlt
* @date 2020/6/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class TenantAuthenticationProvider extends PasswordAuthenticationProvider {
@Override
protected Authentication createSuccessAuthentication(Object principal,
Authentication authentication, UserDetails user) {
TenantUsernamePasswordAuthenticationToken authenticationToken = (TenantUsernamePasswordAuthenticationToken) authentication;
TenantUsernamePasswordAuthenticationToken result = new TenantUsernamePasswordAuthenticationToken(
principal, authentication.getCredentials(), user.getAuthorities(), authenticationToken.getClientId());
result.setDetails(authenticationToken.getDetails());
return result;
}
@Override
public boolean supports(Class<?> authentication) {
return TenantUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
@@ -1,35 +0,0 @@
package com.central.oauth.tenant;
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;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.stereotype.Component;
/**
* @author zlt
* @date 2020/6/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
public class TenantAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private final UserDetailServiceFactory userDetailsServiceFactory;
private final PasswordEncoder passwordEncoder;
public TenantAuthenticationSecurityConfig(UserDetailServiceFactory userDetailsServiceFactory, PasswordEncoder passwordEncoder) {
this.userDetailsServiceFactory = userDetailsServiceFactory;
this.passwordEncoder = passwordEncoder;
}
@Override
public void configure(HttpSecurity http) {
TenantAuthenticationProvider provider = new TenantAuthenticationProvider();
provider.setUserDetailsServiceFactory(userDetailsServiceFactory);
provider.setPasswordEncoder(passwordEncoder);
http.authenticationProvider(provider);
}
}
@@ -1,59 +0,0 @@
package com.central.oauth.tenant;
import com.central.common.context.TenantContextHolder;
import com.central.oauth2.common.token.TenantUsernamePasswordAuthenticationToken;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 替换 UsernamePasswordAuthenticationFilter 增加租户id
*
* @author zlt
* @date 2020/6/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Setter
public class TenantUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private boolean postOnly = true;
public TenantUsernamePasswordAuthenticationFilter () {
super();
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
String clientId = TenantContextHolder.getTenant();
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
TenantUsernamePasswordAuthenticationToken authRequest = new TenantUsernamePasswordAuthenticationToken(username, password, clientId);
setDetails(request, authRequest);
return getAuthenticationManager().authenticate(authRequest);
}
}
@@ -1,132 +0,0 @@
package com.central.oauth.utils;
import com.central.common.utils.JsonUtil;
import com.central.oauth2.common.util.JwtUtils;
import lombok.Getter;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.util.Assert;
import java.util.*;
import static com.central.oauth2.common.constants.IdTokenClaimNames.*;
/**
* Oidc协议的IdToken
*
* @author zlt
* @version 1.0
* @date 2021/4/21
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class OidcIdTokenBuilder {
private final Map<String, Object> claims;
private final KeyProperties keyProperties;
private OidcIdTokenBuilder(KeyProperties keyProperties) {
this.claims = new LinkedHashMap<>();
this.keyProperties = keyProperties;
}
public static OidcIdTokenBuilder builder(KeyProperties keyProperties) {
Assert.notNull(keyProperties, "keyProperties required");
return new OidcIdTokenBuilder(keyProperties);
}
/**
* Use this claim in the resulting {@link OidcIdTokenBuilder}
*
* @param name The claim name
* @param value The claim value
*/
public OidcIdTokenBuilder claim(String name, Object value) {
this.claims.put(name, value);
return this;
}
/**
* Use this audience in the resulting {@link OidcIdTokenBuilder}
*
* @param audience The audience to use
*/
public OidcIdTokenBuilder audience(String audience) {
return claim(AUD, audience);
}
/**
* Use this expiration in the resulting {@link OidcIdTokenBuilder}
*
* @param expiresAt The expiration to use
*/
public OidcIdTokenBuilder expiresAt(long expiresAt) {
return this.claim(EXP, expiresAt);
}
/**
* Use this issued-at timestamp in the resulting {@link OidcIdTokenBuilder}
*
* @param issuedAt The issued-at timestamp to use
*/
public OidcIdTokenBuilder issuedAt(long issuedAt) {
return this.claim(IAT, issuedAt);
}
/**
* Use this issuer in the resulting {@link OidcIdTokenBuilder}
*
* @param issuer The issuer to use
*/
public OidcIdTokenBuilder issuer(String issuer) {
return this.claim(ISS, issuer);
}
/**
* Use this nonce in the resulting {@link OidcIdTokenBuilder}
*
* @param nonce The nonce to use
*/
public OidcIdTokenBuilder nonce(String nonce) {
return this.claim(NONCE, nonce);
}
/**
* Use this subject in the resulting {@link OidcIdTokenBuilder}
*
* @param subject The subject to use
*/
public OidcIdTokenBuilder subject(String subject) {
return this.claim(SUB, subject);
}
/**
* 赋值用户姓名
*/
public OidcIdTokenBuilder name(String name) {
return this.claim(NAME, name);
}
/**
* 赋值用户登录名
*/
public OidcIdTokenBuilder loginName(String loginName) {
return this.claim(L_NAME, loginName);
}
/**
* 赋值用户头像
*/
public OidcIdTokenBuilder picture(String picture) {
return this.claim(PIC, picture);
}
/**
* Build the {@link OidcIdTokenBuilder}
*
* @return The constructed {@link OidcIdTokenBuilder}
*/
public String build() {
return JwtUtils.encodeStr(JsonUtil.toJSONString(claims), keyProperties);
}
}
@@ -1,25 +0,0 @@
package com.central.oauth.utils;
/**
* @author zlt
* @version 1.0
* @date 2021/10/22
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class UsernameHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal();
public static String getContext() {
return contextHolder.get();
}
public static void setContext(String username) {
contextHolder.set(username);
}
public static void clearContext() {
contextHolder.remove();
}
}
+18 -1
View File
@@ -43,4 +43,21 @@ zlt:
enabled: false
includeSqls:
# 应用列表
- com.central.oauth.mapper.ClientMapper.findList
- com.central.oauth.mapper.ClientMapper.findList
springdoc:
swagger-ui:
path: /doc.html
api-docs:
path: /v3/api-docs
group-configs:
- group: 'uaa'
paths-to-match: '/**'
packages-to-scan: com.central.oauth.controller
default-flat-param-object: true
knife4j:
enable: true
setting:
language: zh_cn
swagger-model-name: 认证中心接口文档
@@ -1,9 +1,9 @@
package com.central.oauth2.common.util;
import com.fasterxml.jackson.databind.JsonNode;
/*import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit4.SpringRunner;*/
/**
* 测试工具类
@@ -11,6 +11,7 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author zlt
* @date 2019/7/16
*/
/*
@RunWith(SpringRunner.class)
public class JwtUtilsTest {
@Test
@@ -24,3 +25,4 @@ public class JwtUtilsTest {
System.out.println(isValid);
}
}
*/