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;
}
}