feat: uaa改造为Spring Authorization Server

This commit is contained in:
zlt2000
2023-12-12 10:48:32 +08:00
parent 671ab86543
commit 2a05c6ab91
81 changed files with 2917 additions and 520 deletions
@@ -56,6 +56,7 @@ public class DefaultResourceServerConf {
// 避免iframe同源无法登录许iframe
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
).csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
@@ -5,13 +5,13 @@ import org.springframework.security.oauth2.core.OAuth2Error;
/**
* @author: zlt
* @date: 2023/11/16
* @date: 2023/12/10
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomOAuth2AuthenticationException extends OAuth2AuthenticationException {
public CustomOAuth2AuthenticationException(String msg) {
public class CustomOAuth2AuthorizationException extends OAuth2AuthenticationException {
public CustomOAuth2AuthorizationException(String msg) {
super(new OAuth2Error(msg), msg);
}
}
@@ -35,14 +35,11 @@ public class ClientDto implements Serializable {
private Integer refreshTokenValiditySeconds = 28800;
private String additionalInformation = "{}";
private String autoapprove = "true";
/**
* 是否支持id_token
* token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))
*/
private Boolean supportIdToken = true;
/**
* id_token有效时间(s)
*/
private Integer idTokenValiditySeconds = 60;
private String tokenFormat = "reference";
private Long creatorId;
}
@@ -1,5 +1,6 @@
package com.central.oauth2.common.properties;
import com.central.common.constant.SecurityConstants;
import lombok.Getter;
import lombok.Setter;
@@ -23,11 +24,11 @@ public class PermitProperties {
* 监控中心和swagger需要访问的url
*/
private static final String[] ENDPOINTS = {
"/login.html", "/validata/code/**",
"/v3/api-docs/**", "/*/v3/api-docs/**",
"/doc.html", "/swagger-ui.html", "/swagger-ui/**",
SecurityConstants.LOGIN_PAGE,
SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/**",
"/doc.html", "/swagger-ui.html", "/v3/api-docs/**", "/swagger-ui/**",
"/actuator/**", "/webjars/**", "/druid/**",
"/css/**", "/js/**", "/images/**", "/favicon.ico", "/error",
"/css/**", "/js/**", "/images/**", "/favicon.ico", "/error"
};
/**
@@ -6,6 +6,7 @@ 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.ExpiredObjectListener;
import org.redisson.api.RBucket;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
@@ -28,6 +29,11 @@ import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* 实现 Redis 存储 OAuth2Authorization 对象
* 1. 自动续签token(可配置是否开启)
* 2. 增加 client_id_to_access 和 uname_to_access 两个集合,用于查看在线用户
* 3. 增加过期监听,删除 client_id_to_access 和 uname_to_access 集合的值
*
* @author: zlt
* @date: 2023/11/9
* <p>
@@ -38,7 +44,7 @@ import java.util.*;
@RequiredArgsConstructor
public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationService {
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
private final static Long TIMEOUT = 10L;
private final static Long STATE_TIMEOUT_MINUTES = 10L;
private static final String AUTHORIZATION = "token";
@@ -46,11 +52,32 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
private final RedissonClient redisson;
private final ExpiredObjectListener expiredObjectListener = new ExpiredObjectListener() {
private final static String KEY_SPLIT = "::";
/**
* redis 失效监听,删除集合里的值
* 在 redis.conf 文件中,确保以下设置是启用的:notify-keyspace-events Ex
* 监听的key格式为:token::access_token::${clientId}::${username}::${access_token}
* 例如:token::access_token::webApp::admin::q7ySjsjZoinAx0zUJADqV9P1VmCwYmQDdemwOuhDHjNXVmkzkvquMk_vUBX_Yz40JModOhUwixu-ICH5hti50-KXngBgkn_V1pxu-PZ1YGNkBIDXneE0z4WYx6uFIVHS
*/
@Override
public void onExpired(String name) {
String[] keyArr = name.split(KEY_SPLIT);
if (keyArr.length == 5) {
String clientId = keyArr[2];
String username = keyArr[3];
String accessToken = keyArr[4];
redisListDelete(getClientIdListKey(clientId), accessToken);
redisListDelete(getUnameListKey(clientId, username), accessToken);
}
}
};
@Override
public void save(OAuth2Authorization authorization) {
if (isState(authorization)) {
String token = authorization.getAttribute("state");
this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(TIMEOUT));
this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(STATE_TIMEOUT_MINUTES));
}
if (isCode(authorization)) {
@@ -76,9 +103,22 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
}
private Duration saveAccessToken(OAuth2Authorization authorization) {
return this.saveAccessToken(authorization, false);
}
private Duration saveAccessToken(OAuth2Authorization authorization, boolean isRenew) {
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
Duration duration = this.getExpireSeconds(accessToken);
this.redisBucketSet(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue(), authorization, duration);
RBucket<Integer> listenKeyBucket = redisson.getBucket(buildListenerKey(
OAuth2ParameterNames.ACCESS_TOKEN, authorization.getRegisteredClientId()
, authorization.getPrincipalName(), accessToken.getTokenValue()));
if (!isRenew) {
listenKeyBucket.set(1, duration);
listenKeyBucket.addListener(expiredObjectListener);
} else {
listenKeyBucket.expire(duration);
}
return duration;
}
@@ -94,7 +134,7 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
if (isCode(authorization)) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
.getToken(OAuth2AuthorizationCode.class);
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
}
@@ -154,13 +194,17 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
}
private String buildListenerKey(String type, String clientId, String username, String tokenValue) {
return String.format("%s::%s::%s::%s::%s", AUTHORIZATION, type, clientId, username, tokenValue);
}
private static boolean isState(OAuth2Authorization authorization) {
return Objects.nonNull(authorization.getAttribute("state"));
}
private static boolean isCode(OAuth2Authorization authorization) {
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
.getToken(OAuth2AuthorizationCode.class);
.getToken(OAuth2AuthorizationCode.class);
return Objects.nonNull(authorizationCode);
}
@@ -228,10 +272,6 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
/**
* 更新 access_token 的过期时间
*/
@@ -247,7 +287,7 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>> newTokens = new HashMap<>(tokens);
newTokens.put(OAuth2AccessToken.class, newToken);
tokensField.set(authorization, Collections.unmodifiableMap(newTokens));
this.saveAccessToken(authorization);
this.saveAccessToken(authorization, true);
// 更新集合中的过期时间
this.updateListExpiresAt(this.getClientIdListKey(authorization), Duration.ofSeconds(validitySeconds));
this.updateListExpiresAt(this.getUnameListKey(authorization), Duration.ofSeconds(validitySeconds));
@@ -286,7 +326,6 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
private RBucket<OAuth2Authorization> redisBucketSet(String type, String id, OAuth2Authorization value, Duration duration) {
RBucket<OAuth2Authorization> rBucket = redisson.getBucket(buildKey(type, id), AUTH_CODEC);
rBucket.set(value, duration);
return rBucket;
}
@@ -319,4 +358,8 @@ public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationServi
rList.remove(value);
return rList;
}
private String clientRedisKey(String clientId) {
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
}
}
@@ -0,0 +1,36 @@
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/10
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class MobileAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("mobile_password");
private final Object principal;
private final String credentials;
public MobileAuthenticationToken(String mobile, String password) {
super(GRANT_TYPE);
this.principal = mobile;
this.credentials = password;
super.setAuthenticated(true);
}
public MobileAuthenticationToken(UserDetails user, String password, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
}
}
@@ -0,0 +1,32 @@
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
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class OpenIdAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("openId");
private final Object principal;
public OpenIdAuthenticationToken(String openId) {
super(GRANT_TYPE);
this.principal = openId;
super.setAuthenticated(true);
}
public OpenIdAuthenticationToken(UserDetails principal, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
}
}
@@ -0,0 +1,42 @@
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
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
public class PasswordCodeAuthenticationToken extends BaseAuthenticationToken {
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("password_code");
private final Object principal;
private final String credentials;
private final String deviceId;
private final String validCode;
public PasswordCodeAuthenticationToken(String username, String password, String deviceId, String validCode) {
super(GRANT_TYPE);
this.principal = username;
this.credentials = password;
this.deviceId = deviceId;
this.validCode = validCode;
super.setAuthenticated(true);
}
public PasswordCodeAuthenticationToken(UserDetails user, String password, String deviceId
, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = user;
this.credentials = password;
this.deviceId = deviceId;
this.validCode = null;
}
}
@@ -5,7 +5,7 @@ import com.central.common.constant.CommonConstant;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.LoginAppUser;
import com.central.common.utils.LoginUserUtils;
import com.central.oauth2.common.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.exception.CustomOAuth2AuthorizationException;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
@@ -115,7 +115,7 @@ public class AuthUtils {
public static String[] extractClient(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new CustomOAuth2AuthenticationException("The client information in the request header is empty");
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
return extractHeaderClient(header);
}
@@ -123,7 +123,7 @@ public class AuthUtils {
public static String extractClientId(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new CustomOAuth2AuthenticationException("The client information in the request header is empty");
throw new CustomOAuth2AuthorizationException("The client information in the request header is empty");
}
String[] clientArr = extractHeaderClient(header);
return clientArr[0];
@@ -140,7 +140,7 @@ public class AuthUtils {
String clientStr = new String(decoded, StandardCharsets.UTF_8);
String[] clientArr = clientStr.split(":");
if (clientArr.length != 2) {
throw new CustomOAuth2AuthenticationException("Invalid basic authentication token");
throw new CustomOAuth2AuthorizationException("Invalid basic authentication token");
}
return clientArr;
}
@@ -0,0 +1,197 @@
package com.central.oauth2.common.util;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.core.OAuth2Token;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.InMemoryOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/16
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class OAuth2ConfigurerUtils {
private OAuth2ConfigurerUtils() {
}
public static RegisteredClientRepository getRegisteredClientRepository(HttpSecurity httpSecurity) {
RegisteredClientRepository registeredClientRepository = httpSecurity.getSharedObject(RegisteredClientRepository.class);
if (registeredClientRepository == null) {
registeredClientRepository = getBean(httpSecurity, RegisteredClientRepository.class);
httpSecurity.setSharedObject(RegisteredClientRepository.class, registeredClientRepository);
}
return registeredClientRepository;
}
public static OAuth2AuthorizationService getAuthorizationService(HttpSecurity httpSecurity) {
OAuth2AuthorizationService authorizationService = httpSecurity.getSharedObject(OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = getOptionalBean(httpSecurity, OAuth2AuthorizationService.class);
if (authorizationService == null) {
authorizationService = new InMemoryOAuth2AuthorizationService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationService.class, authorizationService);
}
return authorizationService;
}
public static OAuth2AuthorizationConsentService getAuthorizationConsentService(HttpSecurity httpSecurity) {
OAuth2AuthorizationConsentService authorizationConsentService = httpSecurity.getSharedObject(OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = getOptionalBean(httpSecurity, OAuth2AuthorizationConsentService.class);
if (authorizationConsentService == null) {
authorizationConsentService = new InMemoryOAuth2AuthorizationConsentService();
}
httpSecurity.setSharedObject(OAuth2AuthorizationConsentService.class, authorizationConsentService);
}
return authorizationConsentService;
}
@SuppressWarnings("unchecked")
public static OAuth2TokenGenerator<? extends OAuth2Token> getTokenGenerator(HttpSecurity httpSecurity) {
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = httpSecurity.getSharedObject(OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
tokenGenerator = getOptionalBean(httpSecurity, OAuth2TokenGenerator.class);
if (tokenGenerator == null) {
JwtGenerator jwtGenerator = getJwtGenerator(httpSecurity);
OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer = getAccessTokenCustomizer(httpSecurity);
if (accessTokenCustomizer != null) {
accessTokenGenerator.setAccessTokenCustomizer(accessTokenCustomizer);
}
OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
if (jwtGenerator != null) {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
} else {
tokenGenerator = new DelegatingOAuth2TokenGenerator(
accessTokenGenerator, refreshTokenGenerator);
}
}
httpSecurity.setSharedObject(OAuth2TokenGenerator.class, tokenGenerator);
}
return tokenGenerator;
}
private static JwtGenerator getJwtGenerator(HttpSecurity httpSecurity) {
JwtGenerator jwtGenerator = httpSecurity.getSharedObject(JwtGenerator.class);
if (jwtGenerator == null) {
JwtEncoder jwtEncoder = getJwtEncoder(httpSecurity);
if (jwtEncoder != null) {
jwtGenerator = new JwtGenerator(jwtEncoder);
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer = getJwtCustomizer(httpSecurity);
if (jwtCustomizer != null) {
jwtGenerator.setJwtCustomizer(jwtCustomizer);
}
httpSecurity.setSharedObject(JwtGenerator.class, jwtGenerator);
}
}
return jwtGenerator;
}
private static JwtEncoder getJwtEncoder(HttpSecurity httpSecurity) {
JwtEncoder jwtEncoder = httpSecurity.getSharedObject(JwtEncoder.class);
if (jwtEncoder == null) {
jwtEncoder = getOptionalBean(httpSecurity, JwtEncoder.class);
if (jwtEncoder == null) {
JWKSource<SecurityContext> jwkSource = getJwkSource(httpSecurity);
if (jwkSource != null) {
jwtEncoder = new NimbusJwtEncoder(jwkSource);
}
}
if (jwtEncoder != null) {
httpSecurity.setSharedObject(JwtEncoder.class, jwtEncoder);
}
}
return jwtEncoder;
}
@SuppressWarnings("unchecked")
public static JWKSource<SecurityContext> getJwkSource(HttpSecurity httpSecurity) {
JWKSource<SecurityContext> jwkSource = httpSecurity.getSharedObject(JWKSource.class);
if (jwkSource == null) {
ResolvableType type = ResolvableType.forClassWithGenerics(JWKSource.class, SecurityContext.class);
jwkSource = getOptionalBean(httpSecurity, type);
if (jwkSource != null) {
httpSecurity.setSharedObject(JWKSource.class, jwkSource);
}
}
return jwkSource;
}
private static OAuth2TokenCustomizer<JwtEncodingContext> getJwtCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, JwtEncodingContext.class);
return getOptionalBean(httpSecurity, type);
}
private static OAuth2TokenCustomizer<OAuth2TokenClaimsContext> getAccessTokenCustomizer(HttpSecurity httpSecurity) {
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class, OAuth2TokenClaimsContext.class);
return getOptionalBean(httpSecurity, type);
}
public static AuthorizationServerSettings getAuthorizationServerSettings(HttpSecurity httpSecurity) {
AuthorizationServerSettings authorizationServerSettings = httpSecurity.getSharedObject(AuthorizationServerSettings.class);
if (authorizationServerSettings == null) {
authorizationServerSettings = getBean(httpSecurity, AuthorizationServerSettings.class);
httpSecurity.setSharedObject(AuthorizationServerSettings.class, authorizationServerSettings);
}
return authorizationServerSettings;
}
public static <T> T getBean(HttpSecurity httpSecurity, Class<T> type) {
return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) context.getBean(names[0]);
}
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
throw new NoSuchBeanDefinitionException(type);
}
public static <T> T getOptionalBean(HttpSecurity httpSecurity, Class<T> type) {
Map<String, T> beansMap = BeanFactoryUtils.beansOfTypeIncludingAncestors(
httpSecurity.getSharedObject(ApplicationContext.class), type);
if (beansMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
"Expected single matching bean of type '" + type.getName() + "' but found " +
beansMap.size() + ": " + StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
}
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
}
@SuppressWarnings("unchecked")
public static <T> T getOptionalBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
return names.length == 1 ? (T) context.getBean(names[0]) : null;
}
}
+6 -5
View File
@@ -14,13 +14,10 @@
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
@@ -101,5 +98,9 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
</project>
@@ -1,16 +0,0 @@
package com.central.common.annotation;
import java.lang.annotation.*;
/**
* 请求的方法参数上添加该注解,则注入当前登录账号的应用id
* 例:public void test(@LoginClient String clientId) //注入webApp
*
* @author zlt
* @date 2018/7/24 16:44
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginClient {
}
@@ -1,21 +0,0 @@
package com.central.common.annotation;
import java.lang.annotation.*;
/**
* 请求的方法参数SysUser上添加该注解,则注入当前登录人信息
* 例1:public void test(@LoginUser SysUser user) //只有username 和 roles
* 例2:public void test(@LoginUser(isFull = true) SysUser user) //能获取SysUser对象的所有信息
*
* @author zlt
* @date 2018/7/24 16:44
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginUser {
/**
* 是否查询SysUser对象所有信息,true则通过rpc接口查询
*/
boolean isFull() default false;
}
@@ -1,39 +0,0 @@
package com.central.common.config;
import com.central.common.feign.UserService;
import com.central.common.resolver.ClientArgumentResolver;
import com.central.common.resolver.TokenArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* 默认SpringMVC拦截器
*
* @author zlt
* @date 2019/8/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class DefaultWebMvcConfig implements WebMvcConfigurer {
@Lazy
@Autowired
private UserService userService;
/**
* Token参数解析
*
* @param argumentResolvers 解析类
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//注入用户信息
argumentResolvers.add(new TokenArgumentResolver(userService));
//注入应用信息
argumentResolvers.add(new ClientArgumentResolver());
}
}
@@ -9,6 +9,8 @@ package com.central.common.constant;
* Github: https://github.com/zlt2000
*/
public interface SecurityConstants {
String PROJECT_LICENSE= "http://zlt2000.gitee.io/";
/**
* 用户信息分隔符
*/
@@ -64,6 +66,8 @@ public interface SecurityConstants {
*/
String OAUTH_TOKEN_URL = "/oauth/token";
String OAUTH_CHECK_TOKEN_URL = "/oauth/check_token";
/**
* 默认的处理验证码的url前缀
*/
@@ -161,11 +165,11 @@ public interface SecurityConstants {
/**
* redis中应用对应的token集合的key
*/
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access:";
String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access";
/**
* redis中用户名对应的token集合的key
*/
String REDIS_UNAME_TO_ACCESS = "uname_to_access:";
String REDIS_UNAME_TO_ACCESS = "uname_to_access";
/**
* rsa公钥
*/
@@ -2,7 +2,6 @@ package com.central.common.feign;
import com.central.common.constant.ServiceNameConstants;
import com.central.common.feign.fallback.UserServiceFallbackFactory;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import org.springframework.cloud.openfeign.FeignClient;
@@ -34,7 +33,7 @@ public interface UserService {
* @return
*/
@GetMapping(value = "/users-anon/login", params = "username")
LoginAppUser findByUsername(@RequestParam("username") String username);
SysUser findByUsername(@RequestParam("username") String username);
/**
* 通过手机号查询用户、角色信息
@@ -42,7 +41,7 @@ public interface UserService {
* @param mobile 手机号
*/
@GetMapping(value = "/users-anon/mobile", params = "mobile")
LoginAppUser findByMobile(@RequestParam("mobile") String mobile);
SysUser findByMobile(@RequestParam("mobile") String mobile);
/**
* 根据OpenId查询用户信息
@@ -50,7 +49,7 @@ public interface UserService {
* @param openId openId
*/
@GetMapping(value = "/users-anon/openId", params = "openId")
LoginAppUser findByOpenId(@RequestParam("openId") String openId);
SysUser findByOpenId(@RequestParam("openId") String openId);
/**
@@ -1,7 +1,6 @@
package com.central.common.feign.fallback;
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 org.springframework.cloud.openfeign.FallbackFactory;
@@ -28,21 +27,21 @@ public class UserServiceFallbackFactory implements FallbackFactory<UserService>
}
@Override
public LoginAppUser findByUsername(String username) {
public SysUser findByUsername(String username) {
log.error("通过用户名查询用户异常:{}", username, throwable);
return new LoginAppUser();
return new SysUser();
}
@Override
public LoginAppUser findByMobile(String mobile) {
public SysUser findByMobile(String mobile) {
log.error("通过手机号查询用户异常:{}", mobile, throwable);
return new LoginAppUser();
return new SysUser();
}
@Override
public LoginAppUser findByOpenId(String openId) {
public SysUser findByOpenId(String openId) {
log.error("通过openId查询用户异常:{}", openId, throwable);
return new LoginAppUser();
return new SysUser();
}
/**
@@ -1,6 +1,7 @@
package com.central.common.model;
import java.util.List;
import java.util.Set;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
@@ -39,4 +40,6 @@ public class SysUser extends SuperEntity {
private String oldPassword;
@TableField(exist = false)
private String newPassword;
@TableField(exist = false)
private Set<String> permissions;
}
@@ -1,53 +0,0 @@
package com.central.common.resolver;
import cn.hutool.core.util.StrUtil;
import com.central.common.annotation.LoginClient;
import com.central.common.constant.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import jakarta.servlet.http.HttpServletRequest;
/**
* head中的应用参数注入clientId中
*
* @author zlt
* @date 2019/7/10
*/
@Slf4j
public class ClientArgumentResolver implements HandlerMethodArgumentResolver {
/**
* 入参筛选
*
* @param methodParameter 参数集合
* @return 格式化后的参数
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(LoginClient.class) && methodParameter.getParameterType().equals(String.class);
}
/**
* @param methodParameter 入参集合
* @param modelAndViewContainer model 和 view
* @param nativeWebRequest web相关
* @param webDataBinderFactory 入参解析
* @return 包装对象
*/
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
String clientId = request.getHeader(SecurityConstants.TENANT_HEADER);
if (StrUtil.isBlank(clientId)) {
log.warn("resolveArgument error clientId is empty");
}
return clientId;
}
}
@@ -1,64 +0,0 @@
package com.central.common.resolver;
import com.central.common.annotation.LoginUser;
import com.central.common.constant.SecurityConstants;
import com.central.common.feign.UserService;
import com.central.common.model.SysUser;
import com.central.common.utils.LoginUserUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Token转化SysUser
*
* @author zlt
* @date 2018/12/21
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {
private UserService userService;
public TokenArgumentResolver(UserService userService) {
this.userService = userService;
}
/**
* 入参筛选
*
* @param methodParameter 参数集合
* @return 格式化后的参数
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(SysUser.class);
}
/**
* @param methodParameter 入参集合
* @param modelAndViewContainer model 和 view
* @param nativeWebRequest web相关
* @param webDataBinderFactory 入参解析
* @return 包装对象
*/
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) {
LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class);
boolean isFull = loginUser.isFull();
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
//账号类型
String accountType = request.getHeader(SecurityConstants.ACCOUNT_TYPE_HEADER);
return LoginUserUtils.getCurrentUser(request, isFull);
}
}
@@ -6,6 +6,8 @@ import com.central.common.constant.SecurityConstants;
import com.central.common.context.LoginUserContextHolder;
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 jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
@@ -49,7 +51,10 @@ public class LoginUserUtils {
if (StrUtil.isAllNotBlank(username, userId)) {
if (isFull) {
UserService userService = SpringUtil.getBean(UserService.class);
user = userService.findByUsername(username);
SysUser sysUser = userService.findByUsername(username);
if (sysUser != null) {
return getLoginAppUser(sysUser);
}
} else {
Collection<GrantedAuthority> authorities = new HashSet<>();
if (StrUtil.isNotBlank(roles)) {
@@ -112,6 +117,20 @@ public class LoginUserUtils {
return user;
}
public static LoginAppUser getLoginAppUser(SysUser sysUser) {
List<SysRole> sysRoles = sysUser.getRoles();
Collection<GrantedAuthority> authorities = new HashSet<>();
if (sysRoles != null) {
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
}
return new LoginAppUser(sysUser.getId()
, sysUser.getUsername(), sysUser.getPassword()
, sysUser.getMobile(), sysUser.getPermissions()
, sysUser.getEnabled(), true, true, true
, authorities);
}
@SuppressWarnings("unchecked")
public static LoginAppUser getLoginAppUser(Map<String, Object> userObj) {
return new LoginAppUser(
@@ -1,3 +1,2 @@
com.central.common.feign.fallback.UserServiceFallbackFactory
com.central.common.lock.LockAspect
com.central.common.utils.SpringUtil
com.central.common.lock.LockAspect