diff --git a/README.md b/README.md index f5f7d391..85cfa475 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,7 @@ pig ├── pig-common-seata -- 分布式事务 ├── pig-common-security -- 安全工具类 ├── pig-common-swagger -- 接口文档 - ├── pig-common-feign -- feign 扩展封装 - └── pig-common-test -- oauth2.0 单元测试扩展封装 + └── pig-common-feign -- feign 扩展封装 ├── pig-register -- Nacos Server[8848] ├── pig-gateway -- Spring Cloud Gateway网关[9999] └── pig-upms -- 通用用户权限管理模块 diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfiguration.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfiguration.java index a8914659..0c082cd5 100755 --- a/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfiguration.java +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/AuthorizationServerConfiguration.java @@ -16,7 +16,9 @@ package com.pig4cloud.pig.auth.config; -import com.pig4cloud.pig.auth.support.*; +import com.pig4cloud.pig.auth.support.CustomeOAuth2AccessTokenGenerator; +import com.pig4cloud.pig.auth.support.handler.PigAuthenticationFailureEventHandler; +import com.pig4cloud.pig.auth.support.handler.PigAuthenticationSuccessEventHandler; import com.pig4cloud.pig.auth.support.password.OAuth2ResourceOwnerPasswordAuthenticationConverter; import com.pig4cloud.pig.auth.support.password.OAuth2ResourceOwnerPasswordAuthenticationProvider; import com.pig4cloud.pig.auth.support.sms.OAuth2ResourceOwnerSmsAuthenticationConverter; @@ -63,16 +65,23 @@ public class AuthorizationServerConfiguration { OAuth2AuthorizationService authorizationService) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer<>(); - http.apply(authorizationServerConfigurer.tokenEndpoint( - (tokenEndpoint) -> tokenEndpoint.accessTokenRequestConverter(new DelegatingAuthenticationConverter( - Arrays.asList(new OAuth2ResourceOwnerPasswordAuthenticationConverter(), - new OAuth2ResourceOwnerSmsAuthenticationConverter(), - new OAuth2RefreshTokenAuthenticationConverter(), - new OAuth2ClientCredentialsAuthenticationConverter(), - new OAuth2AuthorizationCodeAuthenticationConverter(), - new OAuth2AuthorizationCodeRequestAuthenticationConverter()))))); - authorizationServerConfigurer.authorizationEndpoint( - authorizationEndpoint -> authorizationEndpoint.consentPage(CUSTOM_CONSENT_PAGE_URI)); + http.apply(authorizationServerConfigurer.tokenEndpoint((tokenEndpoint) -> { + // sas 支持的 Converter + tokenEndpoint.accessTokenRequestConverter(new DelegatingAuthenticationConverter( + Arrays.asList(new OAuth2ResourceOwnerPasswordAuthenticationConverter(), + new OAuth2ResourceOwnerSmsAuthenticationConverter(), + new OAuth2RefreshTokenAuthenticationConverter(), + new OAuth2ClientCredentialsAuthenticationConverter(), + new OAuth2AuthorizationCodeAuthenticationConverter(), + new OAuth2AuthorizationCodeRequestAuthenticationConverter()))); + // 登录成功处理器 + tokenEndpoint.accessTokenResponseHandler(new PigAuthenticationSuccessEventHandler()); + // 登录失败处理器 + tokenEndpoint.errorResponseHandler(new PigAuthenticationFailureEventHandler()); + })); + authorizationServerConfigurer.authorizationEndpoint(authorizationEndpoint -> { + authorizationEndpoint.consentPage(CUSTOM_CONSENT_PAGE_URI); + }); authorizationServerConfigurer.authorizationService(authorizationService); diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfiguration.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfiguration.java index 9f621027..a7c643f7 100755 --- a/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfiguration.java +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/config/WebSecurityConfiguration.java @@ -16,16 +16,14 @@ package com.pig4cloud.pig.auth.config; +import com.pig4cloud.pig.auth.support.handler.FormAuthenticationFailureHandler; +import com.pig4cloud.pig.auth.support.handler.SsoLogoutSuccessHandler; import com.pig4cloud.pig.common.security.component.PigDaoAuthenticationProvider; -import com.pig4cloud.pig.common.security.handler.FormAuthenticationFailureHandler; -import com.pig4cloud.pig.common.security.handler.SsoLogoutSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; /** * 服务安全相关配置 @@ -51,8 +49,11 @@ public class WebSecurityConfiguration { .csrf().disable() // 个性化 formLogin .formLogin().loginPage("/token/login").loginProcessingUrl("/token/form") - .failureHandler(authenticationFailureHandler()).and().logout() - .logoutSuccessHandler(logoutSuccessHandler()).deleteCookies("JSESSIONID").invalidateHttpSession(true); + // SSO登录失败处理 + .failureHandler(new FormAuthenticationFailureHandler()).and().logout() + // SSO登出成功处理 + .logoutSuccessHandler(new SsoLogoutSuccessHandler()).deleteCookies("JSESSIONID") + .invalidateHttpSession(true); // 处理 UsernamePasswordAuthenticationToken http.authenticationProvider(new PigDaoAuthenticationProvider()); @@ -65,22 +66,4 @@ public class WebSecurityConfiguration { return (web) -> web.ignoring().antMatchers("/css/**", "/error"); } - /** - * sso 表单登录失败处理 - * @return FormAuthenticationFailureHandler - */ - @Bean - public AuthenticationFailureHandler authenticationFailureHandler() { - return new FormAuthenticationFailureHandler(); - } - - /** - * SSO 退出逻辑处理 - * @return LogoutSuccessHandler - */ - @Bean - public LogoutSuccessHandler logoutSuccessHandler() { - return new SsoLogoutSuccessHandler(); - } - } diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java index 9ca34e78..531c6a39 100644 --- a/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/endpoint/PigTokenEndpoint.java @@ -21,6 +21,7 @@ import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.pig4cloud.pig.admin.api.entity.SysOauthClientDetails; import com.pig4cloud.pig.admin.api.feign.RemoteClientDetailsService; +import com.pig4cloud.pig.admin.api.vo.TokenVo; import com.pig4cloud.pig.common.security.util.OAuth2EndpointUtils; import com.pig4cloud.pig.common.security.util.OAuth2ErrorCodesExpand; import com.pig4cloud.pig.common.core.constant.CacheConstants; @@ -80,7 +81,7 @@ public class PigTokenEndpoint { private final RemoteClientDetailsService clientDetailsService; - private final RedisTemplate redisTemplate; + private final RedisTemplate redisTemplate; private final CacheManager cacheManager; @@ -192,7 +193,20 @@ public class PigTokenEndpoint { Set keys = redisTemplate.keys(key); List pages = keys.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList()); Page result = new Page(current, size); - result.setRecords(redisTemplate.opsForValue().multiGet(pages)); + + List tokenVoList = redisTemplate.opsForValue().multiGet(pages).stream().map(obj -> { + OAuth2Authorization authorization = (OAuth2Authorization) obj; + TokenVo tokenVo = new TokenVo(); + tokenVo.setClientId(authorization.getRegisteredClientId()); + tokenVo.setId(authorization.getId()); + tokenVo.setUsername(authorization.getPrincipalName()); + OAuth2Authorization.Token accessToken = authorization.getAccessToken(); + tokenVo.setAccessToken(accessToken.getToken().getTokenValue()); + tokenVo.setExpiresAt(accessToken.getToken().getExpiresAt()); + tokenVo.setIssuedAt(accessToken.getToken().getIssuedAt()); + return tokenVo; + }).collect(Collectors.toList()); + result.setRecords(tokenVoList); result.setTotal(keys.size()); return R.ok(result); } diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/CustomeOAuth2AccessTokenGenerator.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/CustomeOAuth2AccessTokenGenerator.java index 554d367e..836d4832 100644 --- a/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/CustomeOAuth2AccessTokenGenerator.java +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/CustomeOAuth2AccessTokenGenerator.java @@ -88,10 +88,9 @@ public class CustomeOAuth2AccessTokenGenerator implements OAuth2TokenGenerator * 表单登录失败处理逻辑 */ diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationFailureEventHandler.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationFailureEventHandler.java new file mode 100644 index 00000000..f8fa4f6f --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationFailureEventHandler.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.support.handler; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.common.core.util.R; +import com.pig4cloud.pig.common.core.util.SpringContextHolder; +import com.pig4cloud.pig.common.log.event.SysLogEvent; +import com.pig4cloud.pig.common.log.util.LogTypeEnum; +import com.pig4cloud.pig.common.log.util.SysLogUtils; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.server.ServletServerHttpResponse; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * @author lengleng + * @date 2022-06-02 + */ +@Slf4j +public class PigAuthenticationFailureEventHandler implements AuthenticationFailureHandler { + + private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter(); + + /** + * Called when an authentication attempt fails. + * @param request the request during which the authentication attempt occurred. + * @param response the response. + * @param exception the exception which was thrown to reject the authentication + * request. + */ + @Override + @SneakyThrows + public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) { + String username = request.getParameter("username"); + log.info("用户:{} 登录失败,异常:{}", username, exception.getLocalizedMessage()); + SysLog logVo = SysLogUtils.getSysLog(); + logVo.setTitle("登录失败"); + logVo.setType(LogTypeEnum.ERROR.getType()); + logVo.setException(exception.getLocalizedMessage()); + // 发送异步日志事件 + Long startTime = System.currentTimeMillis(); + Long endTime = System.currentTimeMillis(); + logVo.setTime(endTime - startTime); + logVo.setCreateBy(username); + logVo.setUpdateBy(username); + SpringContextHolder.publishEvent(new SysLogEvent(logVo)); + // 写出错误信息 + sendErrorResponse(request, response, exception); + } + + private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response, + AuthenticationException exception) throws IOException { + OAuth2Error error = ((OAuth2AuthenticationException) exception).getError(); + ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); + httpResponse.setStatusCode(HttpStatus.BAD_REQUEST); + this.errorHttpResponseConverter.write(R.failed(error.getDescription()), MediaType.APPLICATION_JSON, + httpResponse); + } + +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationSuccessEventHandler.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationSuccessEventHandler.java new file mode 100644 index 00000000..981af492 --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigAuthenticationSuccessEventHandler.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.support.handler; + +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.common.core.util.SpringContextHolder; +import com.pig4cloud.pig.common.log.event.SysLogEvent; +import com.pig4cloud.pig.common.log.util.SysLogUtils; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServletServerHttpResponse; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.OAuth2RefreshToken; +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; +import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter; +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; +import org.springframework.util.CollectionUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.time.temporal.ChronoUnit; +import java.util.Map; + +/** + * @author lengleng + * @date 2022-06-02 + */ +@Slf4j +public class PigAuthenticationSuccessEventHandler implements AuthenticationSuccessHandler { + + private final HttpMessageConverter accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); + + /** + * Called when a user has been successfully authenticated. + * @param request the request which caused the successful authentication + * @param response the response + * @param authentication the Authentication object which was created during + * the authentication process. + */ + @SneakyThrows + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) { + log.info("用户:{} 登录成功", authentication.getPrincipal()); + SecurityContextHolder.getContext().setAuthentication(authentication); + SysLog logVo = SysLogUtils.getSysLog(); + logVo.setTitle("登录成功"); + // 发送异步日志事件 + Long startTime = System.currentTimeMillis(); + Long endTime = System.currentTimeMillis(); + logVo.setTime(endTime - startTime); + logVo.setCreateBy(authentication.getName()); + logVo.setUpdateBy(authentication.getName()); + SpringContextHolder.publishEvent(new SysLogEvent(logVo)); + + // 输出token + sendAccessTokenResponse(request, response, authentication); + } + + private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException { + + OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) authentication; + + OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken(); + OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken(); + Map additionalParameters = accessTokenAuthentication.getAdditionalParameters(); + + OAuth2AccessTokenResponse.Builder builder = OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue()) + .tokenType(accessToken.getTokenType()).scopes(accessToken.getScopes()); + if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) { + builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt())); + } + if (refreshToken != null) { + builder.refreshToken(refreshToken.getTokenValue()); + } + if (!CollectionUtils.isEmpty(additionalParameters)) { + builder.additionalParameters(additionalParameters); + } + OAuth2AccessTokenResponse accessTokenResponse = builder.build(); + ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); + this.accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse); + } + +} diff --git a/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigLogoutSuccessEventHandler.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigLogoutSuccessEventHandler.java new file mode 100644 index 00000000..96ad889a --- /dev/null +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/PigLogoutSuccessEventHandler.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.pig4cloud.pig.auth.support.handler; + +import cn.hutool.core.collection.CollUtil; +import com.pig4cloud.pig.admin.api.entity.SysLog; +import com.pig4cloud.pig.common.core.util.SpringContextHolder; +import com.pig4cloud.pig.common.core.util.WebUtils; +import com.pig4cloud.pig.common.log.event.SysLogEvent; +import com.pig4cloud.pig.common.log.util.SysLogUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.ApplicationListener; +import org.springframework.http.HttpHeaders; +import org.springframework.security.authentication.event.LogoutSuccessEvent; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; +import org.springframework.stereotype.Component; + +/** + * @author zhangran + * @date 2022-06-02 + * + * 事件机制处理退出相关 + */ +@Slf4j +@Component +public class PigLogoutSuccessEventHandler implements ApplicationListener { + + @Override + public void onApplicationEvent(LogoutSuccessEvent event) { + Authentication authentication = (Authentication) event.getSource(); + if (CollUtil.isNotEmpty(authentication.getAuthorities())) { + handle(authentication); + } + } + + /** + * 处理退出成功方法 + *

+ * 获取到登录的authentication 对象 + * @param authentication 登录对象 + */ + public void handle(Authentication authentication) { + log.info("用户:{} 退出成功", authentication.getPrincipal()); + SecurityContextHolder.getContext().setAuthentication(authentication); + + SysLog logVo = SysLogUtils.getSysLog(); + logVo.setTitle("退出成功"); + // 发送异步日志事件 + Long startTime = System.currentTimeMillis(); + Long endTime = System.currentTimeMillis(); + logVo.setTime(endTime - startTime); + + // 设置对应的token + WebUtils.getRequest().ifPresent(request -> logVo.setParams(request.getHeader(HttpHeaders.AUTHORIZATION))); + + // 这边设置ServiceId + if (authentication instanceof OAuth2Authorization) { + OAuth2Authorization auth2Authentication = (OAuth2Authorization) authentication; + logVo.setServiceId(auth2Authentication.getRegisteredClientId()); + } + logVo.setCreateBy(authentication.getName()); + logVo.setUpdateBy(authentication.getName()); + SpringContextHolder.publishEvent(new SysLogEvent(logVo)); + } + +} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/SsoLogoutSuccessHandler.java b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/SsoLogoutSuccessHandler.java similarity index 94% rename from pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/SsoLogoutSuccessHandler.java rename to pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/SsoLogoutSuccessHandler.java index 66b9df67..c092ceaa 100644 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/SsoLogoutSuccessHandler.java +++ b/pig-auth/src/main/java/com/pig4cloud/pig/auth/support/handler/SsoLogoutSuccessHandler.java @@ -1,4 +1,4 @@ -package com.pig4cloud.pig.common.security.handler; +package com.pig4cloud.pig.auth.support.handler; import cn.hutool.core.util.StrUtil; import org.springframework.http.HttpHeaders; @@ -11,7 +11,7 @@ import java.io.IOException; /** * @author lengleng - * @date 2020/10/6 + * @date 2022-06-02 *

* sso 退出功能 ,根据客户端传入跳转 */ diff --git a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java index 092c01b3..7aa7cae2 100755 --- a/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java +++ b/pig-common/pig-common-log/src/main/java/com/pig4cloud/pig/common/log/util/SysLogUtils.java @@ -48,8 +48,6 @@ public class SysLogUtils { HttpServletRequest request = ((ServletRequestAttributes) Objects .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); SysLog sysLog = new SysLog(); - sysLog.setCreateBy(Objects.requireNonNull(getUsername())); - sysLog.setUpdateBy(Objects.requireNonNull(getUsername())); sysLog.setType(LogTypeEnum.NORMAL.getType()); sysLog.setRemoteAddr(ServletUtil.getClientIP(request)); sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI())); diff --git a/pig-common/pig-common-security/pom.xml b/pig-common/pig-common-security/pom.xml index 1fd54e19..4189617e 100755 --- a/pig-common/pig-common-security/pom.xml +++ b/pig-common/pig-common-security/pom.xml @@ -56,17 +56,17 @@ spring-security-oauth2-jose - org.springframework.security + io.springboot.security spring-security-oauth2-authorization-server - 0.3.0 + ${spring.authorization.version} org.springframework spring-webmvc - - org.springframework.boot - spring-boot-starter-jdbc - - + + org.springframework.boot + spring-boot-starter-jdbc + + diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigTokenStoreAutoConfiguration.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigTokenStoreAutoConfiguration.java index 0f0f19c8..681ffa56 100644 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigTokenStoreAutoConfiguration.java +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigTokenStoreAutoConfiguration.java @@ -1,24 +1,12 @@ package com.pig4cloud.pig.common.security.component; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.jose.jwk.source.JWKSource; -import com.nimbusds.jose.proc.SecurityContext; import com.pig4cloud.pig.common.security.service.PigRedisOAuth2AuthorizationConsentService; import com.pig4cloud.pig.common.security.service.PigRedisOAuth2AuthorizationService; -import lombok.SneakyThrows; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.UUID; - /** * @author lengleng * @date 2021/10/16 @@ -35,22 +23,4 @@ public class PigTokenStoreAutoConfiguration { return new PigRedisOAuth2AuthorizationConsentService(redisTemplate); } - @Bean - @SneakyThrows - public JWKSource jwkSource() { - KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); - keyPairGenerator.initialize(2048); - KeyPair keyPair = keyPairGenerator.generateKeyPair(); - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); - - // @formatter:off - RSAKey rsaKey= new RSAKey.Builder(publicKey) - .privateKey(privateKey) - .keyID(UUID.randomUUID().toString()) - .build(); - JWKSet jwkSet = new JWKSet(rsaKey); - return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); - } - } diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractAuthenticationFailureEventHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractAuthenticationFailureEventHandler.java deleted file mode 100644 index 63da2404..00000000 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractAuthenticationFailureEventHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.pig4cloud.pig.common.security.handler; - -import org.springframework.context.ApplicationListener; -import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; - -/** - * @author lengleng - * @date 2019/2/1 认证失败事件处理器 - */ -public abstract class AbstractAuthenticationFailureEventHandler - implements ApplicationListener { - - /** - * Handle an application event. - * @param event the event to respond to - */ - @Override - public void onApplicationEvent(AbstractAuthenticationFailureEvent event) { - AuthenticationException authenticationException = event.getException(); - Authentication authentication = (Authentication) event.getSource(); - - handle(authenticationException, authentication); - } - - /** - * 处理登录成功方法 - *

- * @param authenticationException 登录的authentication 对象 - * @param authentication 登录的authenticationException 对象 - */ - public abstract void handle(AuthenticationException authenticationException, Authentication authentication); - -} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractAuthenticationSuccessEventHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractAuthenticationSuccessEventHandler.java deleted file mode 100755 index 75431289..00000000 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractAuthenticationSuccessEventHandler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.pig4cloud.pig.common.security.handler; - -import cn.hutool.core.collection.CollUtil; -import org.springframework.context.ApplicationListener; -import org.springframework.security.authentication.event.AuthenticationSuccessEvent; -import org.springframework.security.core.Authentication; - -/** - * @author lengleng - * @date 2019/2/1 认证成功事件处理器 - */ -public abstract class AbstractAuthenticationSuccessEventHandler - implements ApplicationListener { - - /** - * Handle an application event. - * @param event the event to respond to - */ - @Override - public void onApplicationEvent(AuthenticationSuccessEvent event) { - Authentication authentication = (Authentication) event.getSource(); - if (CollUtil.isNotEmpty(authentication.getAuthorities())) { - handle(authentication); - } - } - - /** - * 处理登录成功方法 - *

- * 获取到登录的authentication 对象 - * @param authentication 登录对象 - */ - public abstract void handle(Authentication authentication); - -} diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractLogoutSuccessEventHandler.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractLogoutSuccessEventHandler.java deleted file mode 100644 index e1e32830..00000000 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/handler/AbstractLogoutSuccessEventHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.pig4cloud.pig.common.security.handler; - -import cn.hutool.core.collection.CollUtil; -import org.springframework.context.ApplicationListener; -import org.springframework.security.authentication.event.LogoutSuccessEvent; -import org.springframework.security.core.Authentication; - -/** - * @author zhangran - * @date 2021/6/23 退出成功事件处理器 - */ -public abstract class AbstractLogoutSuccessEventHandler implements ApplicationListener { - - /** - * Handle an application event. - * @param event the event to respond to - */ - @Override - public void onApplicationEvent(LogoutSuccessEvent event) { - Authentication authentication = (Authentication) event.getSource(); - if (CollUtil.isNotEmpty(authentication.getAuthorities())) { - handle(authentication); - } - } - - /** - * 处理退出成功方法 - *

- * 获取到登录的authentication 对象 - * @param authentication 登录对象 - */ - public abstract void handle(Authentication authentication); - -} diff --git a/pig-common/pig-common-test/pom.xml b/pig-common/pig-common-test/pom.xml deleted file mode 100755 index 841f3696..00000000 --- a/pig-common/pig-common-test/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - - com.pig4cloud - pig-common - 3.4.10 - - - pig-common-test - jar - - pig oauth 2.0 单元测试工具类 - - - - com.pig4cloud - pig-common-security - - - org.springframework.security - spring-security-test - - - diff --git a/pig-common/pig-common-test/src/main/java/com/pig4cloud/pig/test/annotation/WithMockOAuth2User.java b/pig-common/pig-common-test/src/main/java/com/pig4cloud/pig/test/annotation/WithMockOAuth2User.java deleted file mode 100644 index 2d0f6604..00000000 --- a/pig-common/pig-common-test/src/main/java/com/pig4cloud/pig/test/annotation/WithMockOAuth2User.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.pig4cloud.pig.test.annotation; - -import com.pig4cloud.pig.test.WithMockSecurityContextFactory; -import org.springframework.security.test.context.support.WithSecurityContext; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * @author lengleng - * @date 2020/9/22 - *

- * WithMockOAuth2User 注解 - */ -@Retention(RetentionPolicy.RUNTIME) -@WithSecurityContext(factory = WithMockSecurityContextFactory.class) -public @interface WithMockOAuth2User { - - /** - * 用户名 - */ - String username() default "admin"; - - /** - * 密码 - */ - String password() default "123456"; - -} \ No newline at end of file diff --git a/pig-common/pig-common-test/src/main/java/com/pig4cloud/pig/test/kit/OAuthMockKit.java b/pig-common/pig-common-test/src/main/java/com/pig4cloud/pig/test/kit/OAuthMockKit.java deleted file mode 100644 index 5eec6dca..00000000 --- a/pig-common/pig-common-test/src/main/java/com/pig4cloud/pig/test/kit/OAuthMockKit.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.pig4cloud.pig.test.kit; - -import com.pig4cloud.pig.common.core.util.SpringContextHolder; -import org.springframework.http.HttpHeaders; -import org.springframework.security.oauth2.client.OAuth2ClientContext; -import org.springframework.test.web.servlet.request.RequestPostProcessor; - -/** - * @author lengleng - * @date 2020/9/22 - *

- * Mock 工具类 - */ -public class OAuthMockKit { - - /** - * mock 请求增加统一请求头 - * @return RequestPostProcessor 类似于拦截器 - */ - public static RequestPostProcessor token() { - return mockRequest -> { - OAuth2ClientContext clientContext = SpringContextHolder.getBean(OAuth2ClientContext.class); - String token = clientContext.getAccessToken().getValue(); - mockRequest.addHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer: %s", token)); - return mockRequest; - }; - } - -} diff --git a/pig-common/pom.xml b/pig-common/pom.xml index f4c91e2b..264d484e 100755 --- a/pig-common/pom.xml +++ b/pig-common/pom.xml @@ -40,6 +40,5 @@ pig-common-security pig-common-feign pig-common-swagger - diff --git a/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/TokenVo.java b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/TokenVo.java new file mode 100644 index 00000000..a24354cf --- /dev/null +++ b/pig-upms/pig-upms-api/src/main/java/com/pig4cloud/pig/admin/api/vo/TokenVo.java @@ -0,0 +1,30 @@ +package com.pig4cloud.pig.admin.api.vo; + +import lombok.Data; + +import java.time.Instant; + +/** + * 前端展示令牌管理 + * + * @author lengleng + * @date 2022/6/2 + */ +@Data +public class TokenVo { + + private String id; + + private Long userId; + + private String clientId; + + private String username; + + private String accessToken; + + private Instant issuedAt; + + private Instant expiresAt; + +} diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java index bc5aa24d..b1f2194d 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java @@ -170,7 +170,7 @@ public class UserController { * @return 用户集合 */ @GetMapping("/page") - public R>> getUserPage(Page page, UserDTO userDTO) { + public R> getUserPage(Page page, UserDTO userDTO) { return R.ok(userService.getUserWithRolePage(page, userDTO)); } diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java index 0c22c826..58fdaf1d 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/mapper/SysUserMapper.java @@ -51,7 +51,7 @@ public interface SysUserMapper extends BaseMapper { * @param userDTO 查询参数 * @return list */ - IPage> getUserVosPage(Page page, @Param("query") UserDTO userDTO); + IPage getUserVosPage(Page page, @Param("query") UserDTO userDTO); /** * 通过ID查询用户信息 diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java index 491c4b7a..70051674 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java @@ -49,7 +49,7 @@ public interface SysUserService extends IService { * @param userDTO 参数列表 * @return */ - IPage> getUserWithRolePage(Page page, UserDTO userDTO); + IPage getUserWithRolePage(Page page, UserDTO userDTO); /** * 删除用户 diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java index b652fbaa..eef2466b 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java @@ -142,7 +142,7 @@ public class SysUserServiceImpl extends ServiceImpl impl * @return */ @Override - public IPage> getUserWithRolePage(Page page, UserDTO userDTO) { + public IPage getUserWithRolePage(Page page, UserDTO userDTO) { return baseMapper.getUserVosPage(page, userDTO); } diff --git a/pom.xml b/pom.xml index 0b899ccd..e1cfc727 100755 --- a/pom.xml +++ b/pom.xml @@ -16,231 +16,232 @@ ~ limitations under the License. --> - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.pig4cloud - pig - ${project.artifactId} - 3.5.0-SNAPSHOT - pom - https://www.pig4cloud.com + com.pig4cloud + pig + ${project.artifactId} + 3.5.0-SNAPSHOT + pom + https://www.pig4cloud.com - - 2.7.0 - 2021.0.3 - 2021.0.1.0 - UTF-8 - 1.8 - 1.8 - 2.6.7 - 5.8.2 - 3.5.1 - 2.2.2 - 2.3 - 3.1 - 1.10 - 2.1.0 - 3.0.0 - 2.3.1 - 0.32.0 - http://192.168.0.100:2375 - 192.168.0.100 - pig4cloud - username - password - 4.9.9 - 0.0.32 - + + 2.7.0 + 2021.0.3 + 2021.0.1.0 + UTF-8 + 1.8 + 1.8 + 2.6.7 + 0.3.0 + 5.8.2 + 3.5.1 + 2.2.2 + 2.3 + 3.1 + 1.10 + 2.1.0 + 3.0.0 + 2.3.1 + 0.32.0 + http://192.168.0.100:2375 + 192.168.0.100 + pig4cloud + username + password + 4.9.9 + 0.0.32 + - - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - com.github.ulisesbocchio - jasypt-spring-boot-starter - ${jasypt.version} - - - - org.springframework.boot - spring-boot-starter-actuator - - - - de.codecentric - spring-boot-admin-starter-client - ${spring-boot-admin.version} - - - - org.projectlombok - lombok - provided - - - - org.springframework.boot - spring-boot-starter-test - test - - + + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + com.github.ulisesbocchio + jasypt-spring-boot-starter + ${jasypt.version} + + + + org.springframework.boot + spring-boot-starter-actuator + + + + de.codecentric + spring-boot-admin-starter-client + ${spring-boot-admin.version} + + + + org.projectlombok + lombok + provided + + + + org.springframework.boot + spring-boot-starter-test + test + + - - pig-register - pig-gateway - pig-auth - pig-upms - pig-common - pig-visual - + + pig-register + pig-gateway + pig-auth + pig-upms + pig-common + pig-visual + - - - - - com.pig4cloud - pig-common-bom - ${project.version} - pom - import - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - com.alibaba.cloud - spring-cloud-alibaba-dependencies - ${spring-cloud-alibaba.version} - pom - import - - - + + + + + com.pig4cloud + pig-common-bom + ${project.version} + pom + import + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + com.alibaba.cloud + spring-cloud-alibaba-dependencies + ${spring-cloud-alibaba.version} + pom + import + + + - - ${project.name} - - - src/main/resources - true - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - ${project.build.finalName} - - true - - - - - - repackage - - - - - - io.fabric8 - docker-maven-plugin - ${docker.plugin.version} - - - ${docker.host} - - ${docker.registry} - - - - ${docker.username} - ${docker.password} - - - - - - ${docker.registry}/${docker.namespace}/${project.name}:${project.version} - - ${project.basedir}/Dockerfile - - - - - - - - - - - io.github.git-commit-id - git-commit-id-maven-plugin - ${git.commit.plugin} - - - get-the-git-infos - - revision - - initialize - - - - false - true - - yyyy-MM-dd HH:mm:ss - - ^git.build.(time|version)$ - ^git.commit.(id|message|time).*$ - - - - - - io.spring.javaformat - spring-javaformat-maven-plugin - ${spring.checkstyle.plugin} - - - + + ${project.name} + + + src/main/resources + true + + + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + ${project.build.finalName} + + true + + + + + + repackage + + + + + + io.fabric8 + docker-maven-plugin + ${docker.plugin.version} + + + ${docker.host} + + ${docker.registry} + + + + ${docker.username} + ${docker.password} + + + + + + ${docker.registry}/${docker.namespace}/${project.name}:${project.version} + + ${project.basedir}/Dockerfile + + + + + + + + + + + io.github.git-commit-id + git-commit-id-maven-plugin + ${git.commit.plugin} + + + get-the-git-infos + + revision + + initialize + + + + false + true + + yyyy-MM-dd HH:mm:ss + + ^git.build.(time|version)$ + ^git.commit.(id|message|time).*$ + + + + + + io.spring.javaformat + spring-javaformat-maven-plugin + ${spring.checkstyle.plugin} + + + - - - dev - - - dev - - - - true - - - + + + dev + + + dev + + + + true + + +