diff --git a/pom.xml b/pom.xml index 60bb2608..afcf1578 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,6 @@ 2.3.8.RELEASE 1.1.0.RELEASE 3.24.3 - 5.7.20 3.5.4.1 3.8.1 7.2.28 @@ -47,7 +46,6 @@ 8.0.1.Final 2.7.8 5.1.0 - 2.13.4 1.10 1.12.40 2.2.5.RELEASE @@ -65,6 +63,7 @@ 10.1.11 5.2.1 1.1.1 + 11.7 @@ -213,11 +212,6 @@ ${swagger.butler.version} - - cn.hutool - hutool-all - ${hutool.version} - com.aliyun.oss aliyun-sdk-oss @@ -365,11 +359,6 @@ curator-framework ${curator.version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - org.springframework.security spring-security-oauth2-authorization-server @@ -422,11 +411,6 @@ guava ${guava.version} - - com.fasterxml.jackson.core - jackson-core - ${jackson-databind.version} - org.apache.httpcomponents.client5 httpclient5 @@ -439,6 +423,11 @@ pom import + + com.nimbusds + oauth2-oidc-sdk + ${oauth2-oidc-sdk.version} + diff --git a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java index fc53459f..25b95550 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java +++ b/zlt-business/user-center/src/main/java/com/central/user/controller/SysUserController.java @@ -95,7 +95,7 @@ public class SysUserController { */ @GetMapping(value = "/users-anon/mobile", params = "mobile") @Operation(summary = "根据手机号查询用户") - public SysUser findByMobile(String mobile) { + public LoginAppUser findByMobile(String mobile) { return appUserService.findByMobile(mobile); } @@ -106,7 +106,7 @@ public class SysUserController { */ @GetMapping(value = "/users-anon/openId", params = "openId") @Operation(summary = "根据OpenId查询用户") - public SysUser findByOpenId(String openId) { + public LoginAppUser findByOpenId(String openId) { return appUserService.findByOpenId(openId); } diff --git a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java index 7d98f15b..10d8966d 100644 --- a/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java +++ b/zlt-business/user-center/src/main/java/com/central/user/service/impl/SysUserServiceImpl.java @@ -21,6 +21,8 @@ import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -73,24 +75,26 @@ public class SysUserServiceImpl extends SuperServiceImpl @Override public LoginAppUser getLoginAppUser(SysUser sysUser) { if (sysUser != null) { - LoginAppUser loginAppUser = new LoginAppUser(); - BeanUtils.copyProperties(sysUser, loginAppUser); - List sysRoles = roleUserService.findRolesByUserId(sysUser.getId()); - // 设置角色 - loginAppUser.setRoles(sysRoles); + Collection authorities = new HashSet<>(); + if (sysRoles != null) { + sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode()))); + } + Set permissions = null; if (!CollectionUtils.isEmpty(sysRoles)) { Set roleIds = sysRoles.stream().map(SuperEntity::getId).collect(Collectors.toSet()); List menus = roleMenuMapper.findMenusByRoleIds(roleIds, CommonConstant.PERMISSION); if (!CollectionUtils.isEmpty(menus)) { - Set permissions = menus.stream().map(p -> p.getPath()) + permissions = menus.stream().map(p -> p.getPath()) .collect(Collectors.toSet()); - // 设置权限集合 - loginAppUser.setPermissions(permissions); } } - return loginAppUser; + return new LoginAppUser(sysUser.getId() + , sysUser.getUsername(), sysUser.getPassword() + , sysUser.getMobile(), permissions + , sysUser.getEnabled(), true, true, true + , authorities); } return null; } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml b/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml index f2fedfc5..204e686c 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml @@ -13,8 +13,12 @@ 认证客户端通用组件 - org.springframework.security - spring-security-oauth2-authorization-server + org.springframework.boot + spring-boot-starter-oauth2-authorization-server + + + com.nimbusds + oauth2-oidc-sdk com.zlt diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java index fa788444..45d1a37d 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/AuthClientAutoConfiguration.java @@ -1,7 +1,6 @@ package com.central.oauth2.common; import com.central.oauth2.common.properties.SecurityProperties; -import com.central.oauth2.common.properties.TokenStoreProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; @@ -15,7 +14,7 @@ import org.springframework.context.annotation.ComponentScan; * Blog: http://zlt2000.gitee.io * Github: https://github.com/zlt2000 */ -@EnableConfigurationProperties({SecurityProperties.class, TokenStoreProperties.class}) +@EnableConfigurationProperties({SecurityProperties.class}) @ComponentScan public class AuthClientAutoConfiguration { } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomReactiveAuthorizationServiceIntrospector.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomReactiveAuthorizationServiceIntrospector.java new file mode 100644 index 00000000..61667c4f --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomReactiveAuthorizationServiceIntrospector.java @@ -0,0 +1,54 @@ +package com.central.oauth2.common.component; + +import com.central.common.constant.SecurityConstants; +import com.central.oauth2.common.util.AuthUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; +import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; +import reactor.core.publisher.Mono; + +import java.security.Principal; +import java.util.*; + +/** + * @author zlt + * @version 1.0 + * @date 2023/12/4 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Slf4j +public class CustomReactiveAuthorizationServiceIntrospector implements ReactiveOpaqueTokenIntrospector { + @Override + public Mono introspect(String accessTokenValue) { + return Mono.just(accessTokenValue) + .map(AuthUtils::checkAccessTokenToAuth) + .map(this::convertClaimsSet) + .onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError); + } + + private OAuth2AuthenticatedPrincipal convertClaimsSet(OAuth2Authorization authorization) { + Map claims = new HashMap<>(); + Collection authorities = new ArrayList<>(); + + claims.put(SecurityConstants.CLIENT_ID, authorization.getRegisteredClientId()); + claims.putAll(authorization.getAttributes()); + + Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName()); + if (authentication != null) { + authorities.addAll(authentication.getAuthorities()); + } + + return new OAuth2IntrospectionAuthenticatedPrincipal(authorization.getPrincipalName(), claims, authorities); + } + + private OAuth2IntrospectionException onError(Throwable ex) { + return new OAuth2IntrospectionException(ex.getMessage(), ex); + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/BaseSecurityConfig.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/BaseSecurityConfig.java new file mode 100644 index 00000000..305cb4c0 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/BaseSecurityConfig.java @@ -0,0 +1,131 @@ +package com.central.oauth2.common.config; + +import cn.hutool.core.util.StrUtil; +import com.central.common.constant.SecurityConstants; +import com.central.common.utils.ResponseUtil; +import com.central.common.utils.WebfluxResponseUtil; +import com.central.oauth2.common.properties.SecurityProperties; +import com.central.oauth2.common.service.impl.RedisOAuth2AuthorizationService; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.RSAKey; +import com.nimbusds.jose.jwk.source.ImmutableJWKSet; +import com.nimbusds.jose.jwk.source.JWKSource; +import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.http.HttpServletRequest; +import org.redisson.api.RBucket; +import org.redisson.api.RedissonClient; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtEncoder; +import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.security.web.server.ServerAuthenticationEntryPoint; +import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler; +import org.springframework.web.server.ServerWebExchange; + +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.text.ParseException; +import java.util.UUID; + + +/** + * @author zlt + * @date: 2023/11/25 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +public class BaseSecurityConfig { + @Bean + public OAuth2AuthorizationService oAuth2AuthorizationService(SecurityProperties securityProperties, RedissonClient redisson) { + return new RedisOAuth2AuthorizationService(securityProperties, redisson); + } + + /** + * 鉴权错误处理 + */ + @Bean + public AuthenticationEntryPoint authenticationEntryPoint(ObjectMapper objectMapper) { + return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage()); + } + @Bean + public ServerAuthenticationEntryPoint serverAuthenticationEntryPoint() { + return (exchange, e) -> WebfluxResponseUtil.responseFailed(exchange, HttpStatus.UNAUTHORIZED.value(), e.getMessage()); + } + + /** + * 越权错误处理 + */ + @Bean + public AccessDeniedHandler oAuth2AccessDeniedHandler(ObjectMapper objectMapper) { + return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage()); + } + @Bean + public ServerAccessDeniedHandler serverAccessDeniedHandler() { + return (exchange, e) -> WebfluxResponseUtil.responseFailed(exchange, HttpStatus.FORBIDDEN.value(), e.getMessage()); + } + + /** + * 配置jwk源,使用非对称加密,公开用于检索匹配指定选择器的JWK的方法 + */ + @Bean + public JWKSource jwkSource(RedissonClient redisson) throws ParseException { + RBucket rBucket = redisson.getBucket(SecurityConstants.AUTHORIZATION_JWS_PREFIX_KEY); + String jwkSetCache = rBucket.get(); + JWKSet jwkSet; + // 多个服务共用同一个 jwkSource 对象 + if (StrUtil.isEmpty(jwkSetCache)) { + KeyPair keyPair = generateRsaKey(); + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + RSAKey rsaKey = new RSAKey.Builder(publicKey) + .privateKey(privateKey) + .keyID(UUID.randomUUID().toString()) + .build(); + jwkSet = new JWKSet(rsaKey); + String jwkSetString = jwkSet.toString(Boolean.FALSE); + // 缓存 + boolean success = rBucket.setIfAbsent(jwkSetString); + if (!success) {// 防止同时启动服务时创建了多个jwks + jwkSetCache = rBucket.get(); + jwkSet = JWKSet.parse(jwkSetCache); + } + } else { + // 解析存储的jws + jwkSet = JWKSet.parse(jwkSetCache); + } + return new ImmutableJWKSet<>(jwkSet); + } + + private static KeyPair generateRsaKey() { + KeyPair keyPair; + try { + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); + keyPairGenerator.initialize(2048); + keyPair = keyPairGenerator.generateKeyPair(); + } + catch (Exception ex) { + throw new IllegalStateException(ex); + } + return keyPair; + } + + @Bean + public JwtDecoder jwtDecoder(JWKSource jwkSource) { + return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); + } + + @Bean + public JwtEncoder jwtEncoder(JWKSource jwkSource) { + return new NimbusJwtEncoder(jwkSource); + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/pojo/ClientDto.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/pojo/ClientDto.java new file mode 100644 index 00000000..22fb003f --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/pojo/ClientDto.java @@ -0,0 +1,48 @@ +package com.central.oauth2.common.pojo; + +import lombok.Data; + +import java.io.Serial; +import java.io.Serializable; + +/** + * @author zlt + * @version 1.0 + * @date 2023/12/2 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Data +public class ClientDto implements Serializable { + @Serial + private static final long serialVersionUID = 1L; + private String clientId; + /** + * 应用名称 + */ + private String clientName; + private String resourceIds = ""; + private String clientSecret; + private String clientSecretStr; + private String scope = "all"; + private String authorizedGrantTypes = "authorization_code,password,refresh_token,client_credentials"; + private String webServerRedirectUri; + private String authorities = ""; + + private Integer accessTokenValiditySeconds = 18000; + + private Integer refreshTokenValiditySeconds = 28800; + private String additionalInformation = "{}"; + private String autoapprove = "true"; + /** + * 是否支持id_token + */ + private Boolean supportIdToken = true; + /** + * id_token有效时间(s) + */ + private Integer idTokenValiditySeconds = 60; + + private Long creatorId; +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/PermitProperties.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/PermitProperties.java index 7c5e4591..c861a309 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/PermitProperties.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/PermitProperties.java @@ -23,15 +23,11 @@ public class PermitProperties { * 监控中心和swagger需要访问的url */ private static final String[] ENDPOINTS = { - "/oauth/**", - "/actuator/**", - "/*/v2/api-docs", - "/swagger/api-docs", - "/swagger-ui.html", - "/doc.html", - "/swagger-resources/**", - "/webjars/**", - "/druid/**" + "/login.html", "/validata/code/**", + "/v3/api-docs/**", "/*/v3/api-docs/**", + "/doc.html", "/swagger-ui.html", "/swagger-ui/**", + "/actuator/**", "/webjars/**", "/druid/**", + "/css/**", "/js/**", "/images/**", "/favicon.ico", "/error", }; /** diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/ResourceServerProperties.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/ResourceServerProperties.java new file mode 100644 index 00000000..dcab6931 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/ResourceServerProperties.java @@ -0,0 +1,22 @@ +package com.central.oauth2.common.properties; + +import lombok.Getter; +import lombok.Setter; + +/** + * 资源服务器配置 + * + * @author: zlt + * @date: 2023/11/26 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Setter +@Getter +public class ResourceServerProperties { + /** + * token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt)) + */ + private String tokenFormat = "reference"; +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java index c23adea3..7947eaf9 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/SecurityProperties.java @@ -23,4 +23,6 @@ public class SecurityProperties { private PermitProperties ignore = new PermitProperties(); private ValidateCodeProperties code = new ValidateCodeProperties(); + + private ResourceServerProperties resourceServer = new ResourceServerProperties(); } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/TokenStoreProperties.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/TokenStoreProperties.java deleted file mode 100644 index d49a6c4c..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/properties/TokenStoreProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.central.oauth2.common.properties; - -import lombok.Getter; -import lombok.Setter; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.context.config.annotation.RefreshScope; - -/** - * Token配置 - * - * @author zlt - * @version 1.0 - * @date 2021/5/19 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Setter -@Getter -@ConfigurationProperties(prefix = "zlt.oauth2.token.store") -@RefreshScope -public class TokenStoreProperties { - /** - * token存储类型(redis/db/authJwt/resJwt) - */ - private String type = "redis"; -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java new file mode 100644 index 00000000..36435ef1 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java @@ -0,0 +1,126 @@ +package com.central.oauth2.common.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.StrUtil; +import com.central.common.constant.CommonConstant; +import com.central.common.constant.SecurityConstants; +import com.central.common.context.TenantContextHolder; +import com.central.common.model.LoginAppUser; +import com.central.common.model.SysMenu; +import com.central.oauth2.common.properties.SecurityProperties; +import com.central.oauth2.common.util.AuthUtils; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; +import org.springframework.util.AntPathMatcher; + +import java.security.Principal; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 请求权限判断service + * + * @author zlt + * @date 2018/10/28 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Slf4j +public abstract class DefaultPermissionServiceImpl { + + @Autowired + private SecurityProperties securityProperties; + + private final AntPathMatcher antPathMatcher = new AntPathMatcher(); + + /** + * 查询当前用户拥有的资源权限 + * @param roleCodes 角色code列表,多个以','隔开 + * @return + */ + public abstract List findMenuByRoleCodes(String roleCodes); + + public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) { + // 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现 + if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) { + return true; + } + if (!(authentication instanceof AnonymousAuthenticationToken)) { + //判断是否开启url权限验证 + if (!securityProperties.getAuth().getUrlPermission().getEnable()) { + return true; + } + + OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal = (OAuth2IntrospectionAuthenticatedPrincipal)authentication.getPrincipal(); + //超级管理员admin不需认证 + String username = authenticatedPrincipal.getName(); + if (CommonConstant.ADMIN_USER_NAME.equals(username)) { + return true; + } + Map claims = authenticatedPrincipal.getAttributes(); + String clientId = (String)claims.get(SecurityConstants.CLIENT_ID); + //判断应用黑白名单 + if (!isNeedAuth(clientId)) { + return true; + } + + //判断不进行url权限认证的api,所有已登录用户都能访问的url + for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) { + if (antPathMatcher.match(path, requestURI)) { + return true; + } + } + + Collection grantedAuthorityList = (Collection) authentication.getAuthorities(); + if (CollectionUtil.isEmpty(grantedAuthorityList)) { + log.warn("角色列表为空:{}", authentication.getPrincipal()); + return false; + } + + //保存租户信息 + TenantContextHolder.setTenant(clientId); + + String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", ")); + List menuList = findMenuByRoleCodes(roleCodes); + for (SysMenu menu : menuList) { + if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), requestURI)) { + if (StrUtil.isNotEmpty(menu.getPathMethod())) { + return requestMethod.equalsIgnoreCase(menu.getPathMethod()); + } else { + return true; + } + } + } + } + + return false; + } + + /** + * 判断应用是否满足白名单和黑名单的过滤逻辑 + * @param clientId 应用id + * @return true(需要认证),false(不需要认证) + */ + private boolean isNeedAuth(String clientId) { + boolean result = true; + //白名单 + List includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds(); + //黑名单 + List exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds(); + if (includeClientIds.size() > 0) { + result = includeClientIds.contains(clientId); + } else if(exclusiveClientIds.size() > 0) { + result = !exclusiveClientIds.contains(clientId); + } + return result; + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/RedisOAuth2AuthorizationService.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/RedisOAuth2AuthorizationService.java new file mode 100644 index 00000000..666baeec --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/RedisOAuth2AuthorizationService.java @@ -0,0 +1,322 @@ +package com.central.oauth2.common.service.impl; + +import com.central.common.constant.SecurityConstants; +import com.central.oauth2.common.pojo.ClientDto; +import com.central.oauth2.common.properties.SecurityProperties; +import com.central.oauth2.common.token.CustomAccessToken; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.redisson.api.RBucket; +import org.redisson.api.RList; +import org.redisson.api.RedissonClient; +import org.redisson.codec.SerializationCodec; +import org.springframework.lang.Nullable; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.OAuth2RefreshToken; +import org.springframework.security.oauth2.core.OAuth2Token; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; +import org.springframework.util.Assert; + +import java.lang.reflect.Field; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; + +/** + * @author: zlt + * @date: 2023/11/9 + *

+ * Blog: http://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Slf4j +@RequiredArgsConstructor +public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationService { + private final static SerializationCodec AUTH_CODEC = new SerializationCodec(); + private final static Long TIMEOUT = 10L; + + private static final String AUTHORIZATION = "token"; + + private final SecurityProperties securityProperties; + + private final RedissonClient redisson; + + @Override + public void save(OAuth2Authorization authorization) { + if (isState(authorization)) { + String token = authorization.getAttribute("state"); + this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(TIMEOUT)); + } + + if (isCode(authorization)) { + OAuth2AuthorizationCode authorizationCode = authorization.getToken(OAuth2AuthorizationCode.class).getToken(); + Duration duration = this.getExpireSeconds(authorizationCode); + this.redisBucketSet(OAuth2ParameterNames.CODE, authorizationCode.getTokenValue(), authorization, duration); + } + + if (isRefreshToken(authorization)) { + OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken(); + Duration duration = this.getExpireSeconds(refreshToken); + this.redisBucketSet(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue(), authorization, duration); + } + + if (isAccessToken(authorization)) { + Duration duration = this.saveAccessToken(authorization); + OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); + // 应用id集合 + this.redisListAdd(this.getClientIdListKey(authorization), accessToken.getTokenValue(), duration); + // 应用id + 登录名 集合 + this.redisListAdd(this.getUnameListKey(authorization), accessToken.getTokenValue(), duration); + } + } + + private Duration saveAccessToken(OAuth2Authorization authorization) { + OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); + Duration duration = this.getExpireSeconds(accessToken); + this.redisBucketSet(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue(), authorization, duration); + return duration; + } + + @Override + public void remove(OAuth2Authorization authorization) { + Assert.notNull(authorization, "authorization cannot be null"); + + List keys = new ArrayList<>(); + if (isState(authorization)) { + String token = authorization.getAttribute("state"); + keys.add(buildKey(OAuth2ParameterNames.STATE, token)); + } + + if (isCode(authorization)) { + OAuth2Authorization.Token authorizationCode = authorization + .getToken(OAuth2AuthorizationCode.class); + OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken(); + keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue())); + } + + if (isRefreshToken(authorization)) { + OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken(); + keys.add(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue())); + } + + if (isAccessToken(authorization)) { + OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); + keys.add(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue())); + } + redisson.getKeys().delete(keys.toArray(String[]::new)); + this.removeList(authorization); + } + + @Override + @Nullable + public OAuth2Authorization findById(String id) { + return this.findByToken(id, OAuth2TokenType.ACCESS_TOKEN); + } + + @Override + @Nullable + public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) { + Assert.hasText(token, "token cannot be empty"); + if (tokenType == null) { + tokenType = OAuth2TokenType.ACCESS_TOKEN; + } + OAuth2Authorization authorization = this.redisBucketGet(tokenType.getValue(), token); + + boolean isRenew = securityProperties.getAuth().getRenew().getEnable(); + if (isRenew && tokenType.equals(OAuth2TokenType.ACCESS_TOKEN) && authorization != null) { + this.renew(authorization); + } + + return authorization; + } + + public void remove(String accessToken) { + OAuth2Authorization oAuth2Authorization = this.findById(accessToken); + this.remove(oAuth2Authorization); + } + + public List findTokensByClientId(String clientId) { + RList rList = redisson.getList(this.getClientIdListKey(clientId)); + return rList.readAll(); + } + + public List findTokensByClientIdAndUserName(String clientId, String username) { + RList rList = redisson.getList(this.getUnameListKey(clientId, username)); + return rList.readAll(); + } + + private String buildKey(String type, String id) { + return String.format("%s::%s::%s", AUTHORIZATION, type, id); + } + + private static boolean isState(OAuth2Authorization authorization) { + return Objects.nonNull(authorization.getAttribute("state")); + } + + private static boolean isCode(OAuth2Authorization authorization) { + OAuth2Authorization.Token authorizationCode = authorization + .getToken(OAuth2AuthorizationCode.class); + return Objects.nonNull(authorizationCode); + } + + private static boolean isRefreshToken(OAuth2Authorization authorization) { + return Objects.nonNull(authorization.getRefreshToken()); + } + + private static boolean isAccessToken(OAuth2Authorization authorization) { + return Objects.nonNull(authorization.getAccessToken()); + } + + /** + * 续签 access_token + */ + private void renew(OAuth2Authorization authorization) { + // 判断当前应用是否需要自动续签 + if (checkRenewClientId(authorization.getRegisteredClientId())) { + // 获取过期时长 + long validitySeconds = getAccessTokenValiditySeconds(authorization.getRegisteredClientId()); + if (validitySeconds > 0) { + OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); + long expiresIn = ChronoUnit.SECONDS.between(Instant.now(), accessToken.getExpiresAt()); + double expiresRatio = expiresIn / (double) validitySeconds; + // 判断是否需要续签,当前剩余时间小于过期时长的50%则续签 + if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) { + // 更新AccessToken过期时间 + updateAccessTokenExpiresAt(authorization, validitySeconds); + } + } + } + } + + /** + * 判断应用自动续签是否满足白名单和黑名单的过滤逻辑 + * + * @param clientId 应用id + * @return 是否满足 + */ + private boolean checkRenewClientId(String clientId) { + boolean result = true; + //白名单 + List includeClientIds = securityProperties.getAuth().getRenew().getIncludeClientIds(); + //黑名单 + List exclusiveClientIds = securityProperties.getAuth().getRenew().getExclusiveClientIds(); + if (includeClientIds.size() > 0) { + result = includeClientIds.contains(clientId); + } else if (exclusiveClientIds.size() > 0) { + result = !exclusiveClientIds.contains(clientId); + } + return result; + } + + /** + * 获取token的总有效时长 + * + * @param clientId 应用id + */ + private long getAccessTokenValiditySeconds(String clientId) { + ClientDto clientDetails = (ClientDto)redisson.getBucket(clientRedisKey(clientId)).get(); + if (clientDetails != null) { + return clientDetails.getAccessTokenValiditySeconds(); + } + + //返回默认值 + return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS; + } + + private String clientRedisKey(String clientId) { + return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId; + } + + /** + * 更新 access_token 的过期时间 + */ + @SuppressWarnings("unchecked") + private void updateAccessTokenExpiresAt(OAuth2Authorization authorization, long validitySeconds) { + try { + Class authClazz = authorization.getClass(); + Field tokensField = authClazz.getDeclaredField("tokens"); + tokensField.setAccessible(true); + + Map, OAuth2Authorization.Token> tokens = (Map, OAuth2Authorization.Token>) tokensField.get(authorization); + OAuth2Authorization.Token newToken = this.genateNewAccessToken(authorization.getAccessToken(), validitySeconds); + Map, OAuth2Authorization.Token> newTokens = new HashMap<>(tokens); + newTokens.put(OAuth2AccessToken.class, newToken); + tokensField.set(authorization, Collections.unmodifiableMap(newTokens)); + this.saveAccessToken(authorization); + // 更新集合中的过期时间 + this.updateListExpiresAt(this.getClientIdListKey(authorization), Duration.ofSeconds(validitySeconds)); + this.updateListExpiresAt(this.getUnameListKey(authorization), Duration.ofSeconds(validitySeconds)); + } catch (Exception e) { + log.error("updateAccessTokenExpiresAt-error", e); + throw new RuntimeException(e); + } + } + + + private void removeList(OAuth2Authorization authorization) { + this.redisListDelete(this.getClientIdListKey(authorization), authorization.getId()); + this.redisListDelete(this.getUnameListKey(authorization), authorization.getId()); + } + + private void updateListExpiresAt(String key, Duration duration) { + redisson.getList(key).expire(duration); + } + + private OAuth2Authorization.Token genateNewAccessToken(OAuth2Authorization.Token oldToken, long validitySeconds) { + Instant issuedAt = Instant.now(); + Instant expiresAt = issuedAt.plus(Duration.ofSeconds(validitySeconds)); + + OAuth2AccessToken oldAccessToken = oldToken.getToken(); + OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, + oldAccessToken.getTokenValue(), issuedAt, + expiresAt, oldAccessToken.getScopes()); + return new CustomAccessToken(accessToken, oldToken.getMetadata()); + } + + private Duration getExpireSeconds(OAuth2Token oAuth2Token) { + return Duration.ofSeconds( + ChronoUnit.SECONDS.between(oAuth2Token.getIssuedAt(), oAuth2Token.getExpiresAt())); + } + + private RBucket redisBucketSet(String type, String id, OAuth2Authorization value, Duration duration) { + RBucket rBucket = redisson.getBucket(buildKey(type, id), AUTH_CODEC); + rBucket.set(value, duration); + + return rBucket; + } + + private String getClientIdListKey(OAuth2Authorization authorization) { + return this.getClientIdListKey(authorization.getRegisteredClientId()); + } + private String getClientIdListKey(String clientId) { + return buildKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS, clientId); + } + private String getUnameListKey(OAuth2Authorization authorization) { + return this.getUnameListKey(authorization.getRegisteredClientId(), authorization.getPrincipalName()); + } + private String getUnameListKey(String clientId, String username) { + return buildKey(SecurityConstants.REDIS_UNAME_TO_ACCESS, clientId + "::" + username); + } + + private OAuth2Authorization redisBucketGet(String type, String id) { + return (OAuth2Authorization)redisson.getBucket(buildKey(type, id), AUTH_CODEC).get(); + } + + private RList redisListAdd(String key, String value, Duration duration) { + RList rList = redisson.getList(key); + rList.add(value); + rList.expire(duration); + return rList; + } + + private RList redisListDelete(String key, String value) { + RList rList = redisson.getList(key); + rList.remove(value); + return rList; + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java index 0c53f6b2..4929d9ec 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomAccessToken.java @@ -13,7 +13,7 @@ import java.util.Map; * Github: https://github.com/zlt2000 */ public class CustomAccessToken extends OAuth2Authorization.Token { - protected CustomAccessToken(OAuth2AccessToken token, Map metadata) { + public CustomAccessToken(OAuth2AccessToken token, Map metadata) { super(token, metadata); } } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomWebAuthenticationDetails.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomWebAuthenticationDetails.java deleted file mode 100644 index 4713bcdd..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/CustomWebAuthenticationDetails.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.central.oauth2.common.token; - -import lombok.Getter; - -import java.io.Serializable; - -/** - * 表单登录的认证信息对象 - * - * @author zlt - * @version 1.0 - * @date 2021/7/24 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -@Getter -public class CustomWebAuthenticationDetails implements Serializable { - private static final long serialVersionUID = - 1; - - private final String accountType; - private final String remoteAddress; - private final String sessionId; - - public CustomWebAuthenticationDetails(String remoteAddress, String sessionId, String accountType) { - this.remoteAddress = remoteAddress; - this.sessionId = sessionId; - this.accountType = accountType; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(super.toString()).append("; accountType: ").append(this.getAccountType()); - return sb.toString(); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/MobileAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/MobileAuthenticationToken.java deleted file mode 100644 index 03835f4d..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/MobileAuthenticationToken.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * - */ -package com.central.oauth2.common.token; - -import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.SpringSecurityCoreVersion; - -import java.util.Collection; - -/** - * @author zlt - */ -public class MobileAuthenticationToken extends AbstractAuthenticationToken { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - // ~ Instance fields - // ================================================================================================ - - private final Object principal; - private Object credentials; - - // ~ Constructors - // =================================================================================================== - - /** - * This constructor can be safely used by any code that wishes to create a - * UsernamePasswordAuthenticationToken, as the {@link #isAuthenticated()} - * will return false. - * - */ - public MobileAuthenticationToken(String mobile, String password) { - super(null); - this.principal = mobile; - this.credentials = password; - setAuthenticated(false); - } - - /** - * This constructor should only be used by AuthenticationManager or - * AuthenticationProvider implementations that are satisfied with - * producing a trusted (i.e. {@link #isAuthenticated()} = true) - * authentication token. - * - * @param principal - * @param authorities - */ - public MobileAuthenticationToken(Object principal, Object credentials, - Collection authorities) { - super(authorities); - this.principal = principal; - this.credentials = credentials; - super.setAuthenticated(true); - } - - // ~ Methods - // ======================================================================================================== - - @Override - public Object getCredentials() { - return this.credentials; - } - - @Override - public Object getPrincipal() { - return this.principal; - } - - @Override - public void setAuthenticated(boolean isAuthenticated) { - if (isAuthenticated) { - throw new IllegalArgumentException( - "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); - } - super.setAuthenticated(false); - } - - @Override - public void eraseCredentials() { - super.eraseCredentials(); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/OpenIdAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/OpenIdAuthenticationToken.java deleted file mode 100644 index 04395939..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/OpenIdAuthenticationToken.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.central.oauth2.common.token; - -import org.springframework.security.authentication.AbstractAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.SpringSecurityCoreVersion; - -import java.util.Collection; - -/** - * @author zlt - */ -public class OpenIdAuthenticationToken extends AbstractAuthenticationToken { - - private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; - - // ~ Instance fields - // ================================================================================================ - - private final Object principal; - - // ~ Constructors - // =================================================================================================== - - /** - * This constructor can be safely used by any code that wishes to create a - * UsernamePasswordAuthenticationToken, as the {@link #isAuthenticated()} - * will return false. - * - */ - public OpenIdAuthenticationToken(String openId) { - super(null); - this.principal = openId; - setAuthenticated(false); - } - - /** - * This constructor should only be used by AuthenticationManager or - * AuthenticationProvider implementations that are satisfied with - * producing a trusted (i.e. {@link #isAuthenticated()} = true) - * authentication token. - * - * @param principal - * @param authorities - */ - public OpenIdAuthenticationToken(Object principal, - Collection authorities) { - super(authorities); - this.principal = principal; - super.setAuthenticated(true); - } - - // ~ Methods - // ======================================================================================================== - - @Override - public Object getCredentials() { - return null; - } - - @Override - public Object getPrincipal() { - return this.principal; - } - - @Override - public void setAuthenticated(boolean isAuthenticated) { - if (isAuthenticated) { - throw new IllegalArgumentException( - "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); - } - super.setAuthenticated(false); - } - - @Override - public void eraseCredentials() { - super.eraseCredentials(); - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/PasswordAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/PasswordAuthenticationToken.java new file mode 100644 index 00000000..31a0efed --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/PasswordAuthenticationToken.java @@ -0,0 +1,35 @@ +package com.central.oauth2.common.token; + +import lombok.Getter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.AuthorizationGrantType; + +import java.util.Collection; + +/** + * @author: zlt + * @date: 2023/11/18 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Getter +public class PasswordAuthenticationToken extends BaseAuthenticationToken { + public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("password"); + private final Object principal; + private final String credentials; + + public PasswordAuthenticationToken(String username, String password) { + super(GRANT_TYPE); + this.principal = username; + this.credentials = password; + super.setAuthenticated(true); + } + + public PasswordAuthenticationToken(UserDetails user, String password, Collection authorities) { + super(authorities); + this.principal = user; + this.credentials = password; + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TenantUsernamePasswordAuthenticationToken.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TenantUsernamePasswordAuthenticationToken.java deleted file mode 100644 index d1907825..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/token/TenantUsernamePasswordAuthenticationToken.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.central.oauth2.common.token; - -import lombok.Getter; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; - -import java.util.Collection; - -/** - * 增加租户id,解决不同租户单点登录时角色没变化 - * - * @author zlt - * @date 2020/6/10 - *

- * Blog: http://zlt2000.gitee.io - * Github: https://github.com/zlt2000 - */ -public class TenantUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken { - private static final long serialVersionUID = -5638287853803374687L; - - /** - * 租户id - */ - @Getter - private final String clientId; - - public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials, String clientId) { - super(principal, credentials); - this.clientId = clientId; - } - - public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials, - Collection authorities, String clientId) { - super(principal, credentials, authorities); - this.clientId = clientId; - } -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java index 4ef3d8a1..fed532c8 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java @@ -3,14 +3,12 @@ package com.central.oauth2.common.util; import cn.hutool.extra.spring.SpringUtil; import com.central.common.constant.CommonConstant; import com.central.common.constant.SecurityConstants; -import com.central.common.context.LoginUserContextHolder; -import com.central.common.model.SysUser; +import com.central.common.model.LoginAppUser; +import com.central.common.utils.LoginUserUtils; import com.central.oauth2.common.exception.CustomOAuth2AuthenticationException; import com.central.oauth2.common.token.BaseAuthenticationToken; import lombok.extern.slf4j.Slf4j; -import org.springframework.security.authentication.AnonymousAuthenticationToken; 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.endpoint.OAuth2ParameterNames; @@ -18,8 +16,10 @@ import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import java.nio.charset.StandardCharsets; +import java.security.Principal; import java.util.*; /** @@ -79,36 +79,33 @@ public class AuthUtils { /** * 校验accessToken */ - public static SysUser checkAccessToken(HttpServletRequest request) { + public static LoginAppUser checkAccessToken(HttpServletRequest request) { String accessToken = extractToken(request); return checkAccessToken(accessToken); } - public static SysUser checkAccessToken(String accessTokenValue) { - OAuth2AuthorizationService tokenService = SpringUtil.getBean(OAuth2AuthorizationService.class); - OAuth2Authorization oAuth2Authorization = tokenService.findByToken(accessTokenValue, OAuth2TokenType.ACCESS_TOKEN); - if (oAuth2Authorization == null || oAuth2Authorization.getAccessToken() == null) { - throw new CustomOAuth2AuthenticationException("Invalid access token: " + accessTokenValue); - } else if (oAuth2Authorization.getAccessToken().isExpired()) { - tokenService.remove(oAuth2Authorization); - throw new CustomOAuth2AuthenticationException("Access token expired: " + accessTokenValue); + public static LoginAppUser checkAccessToken(String accessTokenValue) { + OAuth2Authorization authorization = checkAccessTokenToAuth(accessTokenValue); + Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName()); + if (authentication == null) { + throw new OAuth2IntrospectionException("Invalid access token: " + accessTokenValue); } - /*OAuth2Authentication result = tokenStore.readAuthentication(accessToken); - if (result == null) { - throw new OAuth2AuthenticationException("Invalid access token: " + accessTokenValue); - }*/ - // TODO 如何生成 Authentication 对象 - return setContext(null); + return LoginUserUtils.setContext(authentication); } - /** - * 用户信息赋值 context 对象 - */ - public static SysUser setContext(Authentication authentication) { - SecurityContextHolder.getContext().setAuthentication(authentication); - SysUser user = getUser(authentication); - LoginUserContextHolder.setUser(user); - return user; + public static OAuth2Authorization checkAccessTokenToAuth(String accessTokenValue) { + if (accessTokenValue == null) { + throw new OAuth2IntrospectionException("Invalid access token: " + null); + } + OAuth2AuthorizationService authorizationService = SpringUtil.getBean(OAuth2AuthorizationService.class); + OAuth2Authorization authorization = authorizationService.findByToken(accessTokenValue, OAuth2TokenType.ACCESS_TOKEN); + if (authorization == null || authorization.getAccessToken() == null) { + throw new OAuth2IntrospectionException("Invalid access token: " + accessTokenValue); + } else if (authorization.getAccessToken().isExpired()) { + authorizationService.remove(authorization); + throw new OAuth2IntrospectionException("Access token expired: " + accessTokenValue); + } + return authorization; } /** @@ -147,35 +144,6 @@ public class AuthUtils { return clientArr; } - /** - * 获取登陆的用户名 - */ - public static String getUsername(Authentication authentication) { - Object principal = authentication.getPrincipal(); - String username = null; - if (principal instanceof SysUser) { - username = ((SysUser) principal).getUsername(); - } else if (principal instanceof String) { - username = (String) principal; - } - return username; - } - - /** - * 获取登陆的用户对象 - */ - public static SysUser getUser(Authentication authentication) { - SysUser user = null; - if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) { - Object principal = authentication.getPrincipal(); - //客户端模式只返回一个clientId - if (principal instanceof SysUser) { - user = (SysUser)principal; - } - } - return user; - } - /** * 获取登陆的帐户类型 */ diff --git a/zlt-commons/zlt-common-core/pom.xml b/zlt-commons/zlt-common-core/pom.xml index 746451ba..f8d91b5b 100644 --- a/zlt-commons/zlt-common-core/pom.xml +++ b/zlt-commons/zlt-common-core/pom.xml @@ -93,5 +93,13 @@ com.alibaba transmittable-thread-local + + org.springframework.security + spring-security-oauth2-core + + + org.springframework.security + spring-security-oauth2-jose + \ No newline at end of file diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java index 9522a742..4d3888bc 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java @@ -189,4 +189,32 @@ public interface SecurityConstants { * 账号类型参数名 */ String ACCOUNT_TYPE_PARAM_NAME = "account_type"; + + /** + * 协议字段 + */ + String LICENSE_NAME = "license"; + + /** + * 客户端ID + */ + String CLIENT_ID = "clientId"; + + /** + * 用户信息 + */ + String DETAILS_USER = "user_info"; + /** + * 用户ID + */ + String DETAILS_USER_ID = "user_id"; + /** + * 用户名 + */ + String USERNAME = "username"; + + /** + * jwk set缓存前缀 + */ + String AUTHORIZATION_JWS_PREFIX_KEY = "authorization_jws"; } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LoginUserContextHolder.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LoginUserContextHolder.java index 12f4fa5c..900ab452 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LoginUserContextHolder.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LoginUserContextHolder.java @@ -1,7 +1,7 @@ package com.central.common.context; import com.alibaba.ttl.TransmittableThreadLocal; -import com.central.common.model.SysUser; +import com.central.common.model.LoginAppUser; /** * 登录用户holder @@ -13,13 +13,13 @@ import com.central.common.model.SysUser; * Github: https://github.com/zlt2000 */ public class LoginUserContextHolder { - private static final ThreadLocal CONTEXT = new TransmittableThreadLocal<>(); + private static final ThreadLocal CONTEXT = new TransmittableThreadLocal<>(); - public static void setUser(SysUser user) { + public static void setUser(LoginAppUser user) { CONTEXT.set(user); } - public static SysUser getUser() { + public static LoginAppUser getUser() { return CONTEXT.get(); } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/datascope/mp/sql/handler/CreatorDataScopeSqlHandler.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/datascope/mp/sql/handler/CreatorDataScopeSqlHandler.java index 8630b75b..fac8df9b 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/datascope/mp/sql/handler/CreatorDataScopeSqlHandler.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/datascope/mp/sql/handler/CreatorDataScopeSqlHandler.java @@ -6,11 +6,11 @@ import cn.hutool.core.util.StrUtil; import com.central.common.context.LoginUserContextHolder; import com.central.common.enums.DataScope; import com.central.common.feign.UserService; +import com.central.common.model.LoginAppUser; import com.central.common.model.SysRole; -import com.central.common.model.SysUser; import com.central.common.properties.DataScopeProperties; -import org.springframework.beans.factory.annotation.Autowired; +import javax.annotation.Resource; import java.util.List; import java.util.Objects; @@ -21,10 +21,10 @@ import java.util.Objects; */ public class CreatorDataScopeSqlHandler implements SqlHandler{ - @Autowired + @Resource UserService userService; - @Autowired + @Resource private DataScopeProperties dataScopeProperties; /** @@ -35,7 +35,7 @@ public class CreatorDataScopeSqlHandler implements SqlHandler{ */ @Override public String handleScopeSql() { - SysUser user = LoginUserContextHolder.getUser(); + LoginAppUser user = LoginUserContextHolder.getUser(); Assert.notNull(user, "登陆人不能为空"); List roleList = userService.findRolesByUserId(user.getId()); return StrUtil.isBlank(dataScopeProperties.getCreatorIdColumnName()) diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java index 558b5c89..89a5a26d 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java @@ -1,15 +1,13 @@ package com.central.common.model; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +import java.io.Serial; +import java.util.*; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.social.security.SocialUserDetails; -import org.springframework.util.CollectionUtils; - -import com.fasterxml.jackson.annotation.JsonIgnore; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import lombok.Getter; import lombok.Setter; @@ -20,46 +18,49 @@ import lombok.Setter; */ @Getter @Setter -public class LoginAppUser extends SysUser implements SocialUserDetails { +public class LoginAppUser extends User implements OAuth2AuthenticatedPrincipal { + @Serial private static final long serialVersionUID = -3685249101751401211L; - private Set permissions; + @JsonSerialize(using = ToStringSerializer.class) + private final Long id; - /*** - * 权限重写 - */ - @JsonIgnore - @Override - public Collection getAuthorities() { - Collection collection = new HashSet<>(); - if (!CollectionUtils.isEmpty(super.getRoles())) { - super.getRoles().forEach(role -> collection.add(new SimpleGrantedAuthority(role.getCode()))); - } - return collection; + private final String mobile; + + private final Collection permissions; + + private final Map attributes = new HashMap<>(); + + public LoginAppUser() { + super(" ", "", true, true, true, true, new HashSet<>()); + this.id = null; + this.mobile = null; + this.permissions = new HashSet<>(0); + } + + public LoginAppUser(Long id, String username, Collection authorities) { + super(username, "" + , true, true, true, true, authorities); + this.id = id; + this.mobile = null; + this.permissions = new HashSet<>(0); + } + + public LoginAppUser(Long id, String username, String password, String mobile, Collection permissions, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) { + super(username, Optional.ofNullable(password).orElse("") + , enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); + this.id = id; + this.mobile = mobile; + this.permissions = Optional.ofNullable(permissions).orElse(new HashSet<>(0)); } @Override - public boolean isAccountNonExpired() { - return true; + public Map getAttributes() { + return this.attributes; } @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return getEnabled(); - } - - @Override - public String getUserId() { - return getOpenId(); + public String getName() { + return this.getUsername(); } } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java index a05978cb..fceb4ba5 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/LoginUserUtils.java @@ -2,19 +2,20 @@ package com.central.common.utils; import cn.hutool.core.util.StrUtil; import com.central.common.constant.SecurityConstants; +import com.central.common.context.LoginUserContextHolder; import com.central.common.feign.UserService; -import com.central.common.model.SysRole; -import com.central.common.model.SysUser; +import com.central.common.model.LoginAppUser; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.security.oauth2.jwt.Jwt; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; /** * 获取当前登录人工具类 @@ -27,19 +28,17 @@ import java.util.List; * Github: https://github.com/zlt2000 */ public class LoginUserUtils { + private final static String ATT_PERMISSIONS = "permissions"; + /** * 获取当前登录人 */ - public static SysUser getCurrentUser(HttpServletRequest request, boolean isFull) { - SysUser user = null; + public static LoginAppUser getCurrentUser(HttpServletRequest request, boolean isFull) { + LoginAppUser user = null; Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) { - Object principal = authentication.getPrincipal(); - //客户端模式只返回一个clientId - if (principal instanceof SysUser) { - user = (SysUser)principal; - } + user = getUser(authentication); } if (user == null) { String userId = request.getHeader(SecurityConstants.USER_ID_HEADER); @@ -49,27 +48,20 @@ public class LoginUserUtils { if (StrUtil.isAllNotBlank(username, userId)) { if (isFull) { UserService userService = SpringUtil.getBean(UserService.class); - user = userService.selectByUsername(username); + user = userService.findByUsername(username); } else { - user = new SysUser(); - user.setId(Long.valueOf(userId)); - user.setUsername(username); - } - if (StrUtil.isNotBlank(roles)) { - List sysRoleList = new ArrayList<>(); - Arrays.stream(roles.split(",")).forEach(role -> { - SysRole sysRole = new SysRole(); - sysRole.setCode(role); - sysRoleList.add(sysRole); - }); - user.setRoles(sysRoleList); + Collection authorities = new HashSet<>(); + if (StrUtil.isNotBlank(roles)) { + Arrays.stream(roles.split(",")).forEach(role -> authorities.add(new SimpleGrantedAuthority(role))); + } + return new LoginAppUser(Long.valueOf(userId), username, authorities); } } } return user; } - public static SysUser getCurrentUser(boolean isFull) { + public static LoginAppUser getCurrentUser(boolean isFull) { // 从请求上下文里获取 Request 对象 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest contextRequest = requestAttributes.getRequest(); @@ -78,4 +70,65 @@ public class LoginUserUtils { } return null; } + + /** + * 获取登陆的用户对象 + */ + public static LoginAppUser getUser(Authentication authentication) { + LoginAppUser user = null; + if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) { + Object principal = authentication.getPrincipal(); + //客户端模式只返回一个clientId + if (principal instanceof LoginAppUser) { + user = (LoginAppUser) principal; + } else if (principal instanceof Jwt jwt) { + Map userMap = jwt.getClaim(SecurityConstants.DETAILS_USER); + user = getLoginAppUser(userMap); + } + } + return user; + } + + /** + * 获取登陆的用户名 + */ + public static String getUsername(Authentication authentication) { + LoginAppUser user = getUser(authentication); + String username = null; + if (user != null) { + username = user.getUsername(); + } + return username; + } + + /** + * 用户信息赋值 context 对象 + */ + public static LoginAppUser setContext(Authentication authentication) { + SecurityContextHolder.getContext().setAuthentication(authentication); + LoginAppUser user = getUser(authentication); + LoginUserContextHolder.setUser(user); + return user; + } + + @SuppressWarnings("unchecked") + public static LoginAppUser getLoginAppUser(Map userObj) { + return new LoginAppUser( + (Long)userObj.get("id"), + (String)userObj.get("username"), + (String)userObj.get("password"), + (String)userObj.get("mobile"), + (Collection)userObj.get(ATT_PERMISSIONS), + Optional.ofNullable((Boolean)userObj.get("enabled")).orElse(true), + true, true, true, + getGrantedAuthoritys((List>)userObj.get("authorities"))); + } + private static Collection getGrantedAuthoritys(List> authorities) { + if (authorities != null) { + List result = new ArrayList<>(authorities.size()); + authorities.forEach(e -> result.add(new SimpleGrantedAuthority(e.get("role")))); + return result; + } + return null; + } } diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java index b169e2e5..f1f875f8 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/LoginUserFilter.java @@ -1,7 +1,7 @@ package com.central.common.filter; import com.central.common.context.LoginUserContextHolder; -import com.central.common.model.SysUser; +import com.central.common.model.LoginAppUser; import com.central.common.utils.LoginUserUtils; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; @@ -30,7 +30,7 @@ public class LoginUserFilter extends OncePerRequestFilter { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { try { - SysUser user = LoginUserUtils.getCurrentUser(request, false); + LoginAppUser user = LoginUserUtils.getCurrentUser(request, false); LoginUserContextHolder.setUser(user); filterChain.doFilter(request, response); } finally { diff --git a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml index ddf27ba3..ef870923 100644 --- a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml @@ -37,5 +37,10 @@ spring-boot-configuration-processor true + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java index edfa0d36..60196b5c 100644 --- a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java +++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/RedisAutoConfigure.java @@ -9,7 +9,6 @@ import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; diff --git a/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/component/RedissonAutoConfigCustomizers.java b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/component/RedissonAutoConfigCustomizers.java new file mode 100644 index 00000000..0f6e4986 --- /dev/null +++ b/zlt-commons/zlt-redis-spring-boot-starter/src/main/java/com/central/common/redis/component/RedissonAutoConfigCustomizers.java @@ -0,0 +1,24 @@ +package com.central.common.redis.component; + +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.redisson.codec.JsonJacksonCodec; +import org.redisson.config.Config; +import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer; +import org.springframework.stereotype.Component; + +/** + * @author: zlt + * @date: 2023/11/21 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Component +public class RedissonAutoConfigCustomizers implements RedissonAutoConfigurationCustomizer { + @Override + public void customize(Config configuration) { + JsonJacksonCodec jacksonCodec = new JsonJacksonCodec(); + jacksonCodec.getObjectMapper().registerModule(new JavaTimeModule()); + configuration.setCodec(jacksonCodec); + } +} diff --git a/zlt-gateway/sc-gateway/pom.xml b/zlt-gateway/sc-gateway/pom.xml index ccd5f63d..b8538b5d 100644 --- a/zlt-gateway/sc-gateway/pom.xml +++ b/zlt-gateway/sc-gateway/pom.xml @@ -54,10 +54,11 @@ - + org.springframework.cloud @@ -78,10 +79,6 @@ knife4j-gateway-spring-boot-starter - com.baomidou mybatis-plus-extension diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java new file mode 100644 index 00000000..1aa67764 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2ServerAuthSuccessHandler.java @@ -0,0 +1,57 @@ +package com.central.gateway.auth; + +import cn.hutool.core.collection.CollectionUtil; +import com.central.common.constant.SecurityConstants; +import com.central.common.model.LoginAppUser; +import com.central.common.utils.LoginUserUtils; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; +import org.springframework.security.web.server.WebFilterExchange; +import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.security.Principal; +import java.util.Map; + +/** + * 认证成功处理类 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +public class Oauth2ServerAuthSuccessHandler implements ServerAuthenticationSuccessHandler { + @Override + public Mono onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { + MultiValueMap headerValues = new LinkedMultiValueMap<>(4); + Object principal = authentication.getPrincipal(); + + if (principal instanceof OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal) { + Map claims = authenticatedPrincipal.getAttributes(); + Authentication auth = (Authentication)claims.get(Principal.class.getName()); + LoginAppUser user = LoginUserUtils.getUser(auth); + if (user != null) { + headerValues.add(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId())); + headerValues.add(SecurityConstants.USER_HEADER, user.getUsername()); + } + + headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ",")); + headerValues.add(SecurityConstants.TENANT_HEADER, (String)claims.get(SecurityConstants.CLIENT_ID)); + headerValues.add(SecurityConstants.ACCOUNT_TYPE_HEADER, (String)claims.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME)); + } + + ServerWebExchange exchange = webFilterExchange.getExchange(); + ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate() + .headers(h -> h.addAll(headerValues)) + .build(); + + ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build(); + return webFilterExchange.getChain().filter(build); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java new file mode 100644 index 00000000..15987deb --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java @@ -0,0 +1,56 @@ +package com.central.gateway.auth; + +import com.central.common.model.SysMenu; +import com.central.gateway.feign.AsynMenuService; +import com.central.oauth2.common.service.impl.DefaultPermissionServiceImpl; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.server.authorization.AuthorizationContext; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import javax.annotation.Resource; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Future; + +/** + * url权限认证 + * + * @author zlt + * @date 2019/10/6 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Slf4j +@Component +public class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager { + @Resource + private AsynMenuService asynMenuService; + + @Override + public Mono check(Mono authentication, AuthorizationContext authorizationContext) { + return authentication.map(auth -> { + ServerWebExchange exchange = authorizationContext.getExchange(); + ServerHttpRequest request = exchange.getRequest(); + boolean isPermission = super.hasPermission(auth, request.getMethod().name(), request.getURI().getPath()); + return new AuthorizationDecision(isPermission); + }).defaultIfEmpty(new AuthorizationDecision(false)); + } + + @Override + public List findMenuByRoleCodes(String roleCodes) { + Future> futureResult = asynMenuService.findByRoleCodes(roleCodes); + try { + return futureResult.get(); + } catch (Exception e) { + log.error("asynMenuService.findMenuByRoleCodes-error", e); + } + return Collections.emptyList(); + } +} \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java new file mode 100644 index 00000000..80dca0be --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java @@ -0,0 +1,87 @@ +package com.central.gateway.config; + +import com.central.gateway.auth.*; +import com.central.oauth2.common.component.CustomReactiveAuthorizationServiceIntrospector; +import com.central.oauth2.common.config.BaseSecurityConfig; +import com.central.oauth2.common.properties.SecurityProperties; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.SecurityWebFiltersOrder; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.oauth2.server.resource.authentication.OpaqueTokenReactiveAuthenticationManager; +import org.springframework.security.oauth2.server.resource.web.server.authentication.ServerBearerTokenAuthenticationConverter; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.ServerAuthenticationEntryPoint; +import org.springframework.security.web.server.authentication.AuthenticationWebFilter; +import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler; +import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler; + +/** + * 资源服务器 + * + * @author: zlt + * @date: 2023/11/25 + *

+ * Blog: https://zlt2000.gitee.io + * Github: https://github.com/zlt2000 + */ +@Configuration +@EnableWebFluxSecurity +@Slf4j +@Import(BaseSecurityConfig.class) +public class ResourceServerConfiguration { + @Bean + public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http + , SecurityProperties securityProperties, PermissionAuthManager permissionAuthManager + , ServerAuthenticationEntryPoint authenticationEntryPoint, ServerAccessDeniedHandler accessDeniedHandler) { + http.csrf(ServerHttpSecurity.CsrfSpec::disable) + .cors(ServerHttpSecurity.CorsSpec::disable) + .headers(hSpec -> hSpec.frameOptions(ServerHttpSecurity.HeaderSpec.FrameOptionsSpec::disable)) + .httpBasic(ServerHttpSecurity.HttpBasicSpec::disable) + .exceptionHandling(e -> { + e.authenticationEntryPoint(authenticationEntryPoint) + .accessDeniedHandler(accessDeniedHandler); + }); + + http.authorizeExchange(exchange -> { + if (securityProperties.getAuth().getHttpUrls().length > 0) { + exchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated(); + } + if (securityProperties.getIgnore().getUrls().length > 0) { + exchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll(); + } + exchange.pathMatchers(HttpMethod.OPTIONS).permitAll() + .anyExchange().access(permissionAuthManager); + }); + + http.addFilterAt(this.getAuthWebFilter(authenticationEntryPoint) + , SecurityWebFiltersOrder.AUTHENTICATION); + + return http.build(); + } + + private AuthenticationWebFilter getAuthWebFilter(ServerAuthenticationEntryPoint authenticationEntryPoint) { + OpaqueTokenReactiveAuthenticationManager authenticationManager = + new OpaqueTokenReactiveAuthenticationManager( + new CustomReactiveAuthorizationServiceIntrospector()); + ServerBearerTokenAuthenticationConverter authenticationConverter = new ServerBearerTokenAuthenticationConverter(); + authenticationConverter.setAllowUriQueryParameter(true); + + AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(authenticationManager); + oauth2.setServerAuthenticationConverter(authenticationConverter); + oauth2.setAuthenticationFailureHandler(getFailureHandler(authenticationEntryPoint)); + oauth2.setAuthenticationSuccessHandler(new Oauth2ServerAuthSuccessHandler()); + return oauth2; + } + + private ServerAuthenticationEntryPointFailureHandler getFailureHandler(ServerAuthenticationEntryPoint authenticationEntryPoint) { + ServerAuthenticationEntryPointFailureHandler failureHandler = + new ServerAuthenticationEntryPointFailureHandler(authenticationEntryPoint); + failureHandler.setRethrowAuthenticationServiceException(false); + return failureHandler; + } +} diff --git a/zlt-gateway/sc-gateway/src/main/resources/application.yml b/zlt-gateway/sc-gateway/src/main/resources/application.yml index b73d27b3..c5f14ed8 100644 --- a/zlt-gateway/sc-gateway/src/main/resources/application.yml +++ b/zlt-gateway/sc-gateway/src/main/resources/application.yml @@ -96,10 +96,6 @@ knife4j: url: /api-file/v3/api-docs/default context-path: /api-file -# discover: -# version: openapi3 -# excluded-services: ${spring.application.name} - zlt: oauth2: token: diff --git a/zlt-uaa/pom.xml b/zlt-uaa/pom.xml index 5efd2379..53d17a81 100644 --- a/zlt-uaa/pom.xml +++ b/zlt-uaa/pom.xml @@ -21,10 +21,10 @@ com.zlt zlt-common-spring-boot-starter - + com.zlt zlt-db-spring-boot-starter @@ -50,6 +50,10 @@ com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery + + org.springframework.boot + spring-boot-starter-oauth2-authorization-server + org.springframework.social spring-social-security diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java b/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java index c419e99d..c9afe37e 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/IClientService.java @@ -26,4 +26,6 @@ public interface IClientService extends ISuperService { void delClient(long id); Client loadClientByClientId(String clientId); + + void loadAllClientToCache(); } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java index bdeda622..a3148273 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/ZltUserDetailsService.java @@ -3,7 +3,6 @@ package com.central.oauth.service; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.social.security.SocialUserDetails; /** * @author zlt @@ -31,5 +30,5 @@ public interface ZltUserDetailsService extends UserDetailsService { * 根据用户id/openId查询用户 * @param userId 用户id/openId */ - SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException; + UserDetails loadUserByUserId(String userId) throws UsernameNotFoundException; } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java index bfc2a751..7a7fa3e7 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ClientServiceImpl.java @@ -8,13 +8,15 @@ import com.central.common.context.LoginUserContextHolder; import com.central.common.lock.DistributedLock; import com.central.common.model.PageResult; import com.central.common.model.Result; -import com.central.common.redis.template.RedisRepository; import com.central.common.service.impl.SuperServiceImpl; import com.central.oauth.mapper.ClientMapper; import com.central.oauth.model.Client; import com.central.oauth.service.IClientService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; +import org.redisson.api.RBucket; +import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -29,18 +31,16 @@ import java.util.Map; * Github: https://github.com/zlt2000 */ @Slf4j +@RequiredArgsConstructor @Service public class ClientServiceImpl extends SuperServiceImpl implements IClientService { private final static String LOCK_KEY_CLIENTID = "clientId:"; - @Autowired - private RedisRepository redisRepository; + private final RedissonClient redisson; - @Autowired - private PasswordEncoder passwordEncoder; + private final PasswordEncoder passwordEncoder; - @Autowired - private DistributedLock lock; + private final DistributedLock lock; @Override public Result saveClient(Client client) throws Exception { @@ -53,6 +53,9 @@ public class ClientServiceImpl extends SuperServiceImpl im , LOCK_KEY_CLIENTID+clientId , new QueryWrapper().eq("client_id", clientId) , clientId + "已存在"); + + redisson.getBucket(clientRedisKey(clientId)).set(client); + return Result.succeed("操作成功"); } @@ -73,14 +76,27 @@ public class ClientServiceImpl extends SuperServiceImpl im public void delClient(long id) { String clientId = baseMapper.selectById(id).getClientId(); baseMapper.deleteById(id); - redisRepository.del(clientRedisKey(clientId)); + redisson.getBucket(clientRedisKey(clientId)).delete(); } @Override public Client loadClientByClientId(String clientId) { + RBucket clientBucket = redisson.getBucket(clientRedisKey(clientId)); + Client client = clientBucket.get(); + if (client != null) { + return client; + } QueryWrapper wrapper = Wrappers.query(); wrapper.eq("client_id", clientId); - return this.getOne(wrapper); + client = this.getOne(wrapper); + clientBucket.set(client); + return client; + } + + @Override + public void loadAllClientToCache() { + List clientList = this.list(); + clientList.forEach(c -> redisson.getBucket(clientRedisKey(c.getClientId())).set(c)); } private String clientRedisKey(String clientId) { diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java index e227fa07..0f505921 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/UserDetailServiceImpl.java @@ -8,7 +8,6 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.social.security.SocialUserDetails; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -42,7 +41,7 @@ public class UserDetailServiceImpl implements ZltUserDetailsService { } @Override - public SocialUserDetails loadUserByUserId(String openId) { + public UserDetails loadUserByUserId(String openId) { LoginAppUser loginAppUser = userService.findByOpenId(openId); return checkUser(loginAppUser); } diff --git a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java index 04cce984..dae161a3 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java +++ b/zlt-uaa/src/main/java/com/central/oauth/service/impl/ValidateCodeServiceImpl.java @@ -4,8 +4,8 @@ import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import com.central.common.constant.SecurityConstants; import com.central.common.feign.UserService; +import com.central.common.model.LoginAppUser; import com.central.common.model.Result; -import com.central.common.model.SysUser; import com.central.common.redis.template.RedisRepository; import com.central.oauth.exception.ValidateCodeException; import com.central.oauth.service.IValidateCodeService; @@ -61,7 +61,7 @@ public class ValidateCodeServiceImpl implements IValidateCodeService { return Result.failed("验证码未失效,请失效后再次申请"); } - SysUser user = userService.findByMobile(mobile); + LoginAppUser user = userService.findByMobile(mobile); if (user == null) { log.error("根据用户手机号{}查询用户为空", mobile); return Result.failed("手机号不存在");