feat: 替换swagger2为OpenAPI3

This commit is contained in:
zlt2000
2023-11-24 17:28:19 +08:00
parent 61640eb237
commit 387b524f67
67 changed files with 494 additions and 2380 deletions
@@ -1,86 +0,0 @@
package com.central.oauth2.common.config;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.annotation.Resource;
/**
* @author zlt
*/
@Import(DefaultSecurityHandlerConfig.class)
public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Resource
private AuthenticationEntryPoint authenticationEntryPoint;
@Resource
private OAuth2WebSecurityExpressionHandler expressionHandler;
@Resource
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
@Autowired
private SecurityProperties securityProperties;
@Resource
private TokenExtractor tokenExtractor;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenStore(tokenStore)
.stateless(true)
.authenticationEntryPoint(authenticationEntryPoint)
.expressionHandler(expressionHandler)
.accessDeniedHandler(oAuth2AccessDeniedHandler)
.tokenExtractor(tokenExtractor);
}
@Override
public void configure(HttpSecurity http) throws Exception {
AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = setHttp(http)
.authorizeHttpRequests()
.requestMatchers(securityProperties.getIgnore().getUrls()).permitAll()
.requestMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest();
setAuthenticate(authorizedUrl);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.httpBasic().disable()
.headers()
.frameOptions().disable()
.and()
.csrf().disable();
}
/**
* url权限控制,默认是认证就通过,可以重写实现个性化
* @param authorizedUrl
*/
public HttpSecurity setAuthenticate(AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl) {
return authorizedUrl.authenticated().and();
}
/**
* 留给子类重写扩展功能
* @param http
*/
public HttpSecurity setHttp(HttpSecurity http) {
return http;
}
}
@@ -1,54 +0,0 @@
package com.central.oauth2.common.config;
import com.central.common.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.expression.OAuth2WebSecurityExpressionHandler;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author zlt
*/
public class DefaultSecurityHandlerConfig {
@Resource
private ObjectMapper objectMapper;
/**
* 未登录,返回401
*
* @return
*/
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
}
@Bean
public OAuth2WebSecurityExpressionHandler oAuth2WebSecurityExpressionHandler(ApplicationContext applicationContext) {
OAuth2WebSecurityExpressionHandler expressionHandler = new OAuth2WebSecurityExpressionHandler();
expressionHandler.setApplicationContext(applicationContext);
return expressionHandler;
}
/**
* 处理spring security oauth 处理失败返回消息格式
*/
@Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException {
ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
}
};
}
}
@@ -1,89 +0,0 @@
package com.central.oauth2.common.constants;
/**
* id_token属性名常量
*
* @author zlt
* @version 1.0
* @date 2021/4/23
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class IdTokenClaimNames {
/**
* {@code iss} - the Issuer identifier
*/
public final static String ISS = "iss";
/**
* {@code sub} - the Subject identifier
*/
public final static String SUB = "sub";
/**
* {@code aud} - the Audience(s) that the ID Token is intended for
*/
public final static String AUD = "aud";
/**
* {@code exp} - the Expiration time on or after which the ID Token MUST NOT be accepted
*/
public final static String EXP = "exp";
/**
* {@code iat} - the time at which the ID Token was issued
*/
public final static String IAT = "iat";
/**
* {@code auth_time} - the time when the End-User authentication occurred
*/
public final static String AUTH_TIME = "auth_time";
/**
* {@code nonce} - a {@code String} value used to associate a Client session with an ID Token,
* and to mitigate replay attacks.
*/
public final static String NONCE = "nonce";
/**
* {@code acr} - the Authentication Context Class Reference
*/
public final static String ACR = "acr";
/**
* {@code amr} - the Authentication Methods References
*/
public final static String AMR = "amr";
/**
* {@code azp} - the Authorized party to which the ID Token was issued
*/
public final static String AZP = "azp";
/**
* {@code at_hash} - the Access Token hash value
*/
public final static String AT_HASH = "at_hash";
/**
* {@code c_hash} - the Authorization Code hash value
*/
public final static String C_HASH = "c_hash";
/**
* {@code name} - 用户姓名
*/
public final static String NAME = "name";
/**
* {@code login_name} - 登录名
*/
public final static String L_NAME = "login_name";
/**
* {@code picture} - 头像照片
*/
public final static String PIC = "picture";
}
@@ -1,96 +0,0 @@
package com.central.oauth2.common.converter;
import com.central.common.model.LoginAppUser;
import com.central.common.model.SysUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 优化自org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter
* jwt返回的principal改为返回SysUser,增加扩展字段
*
* @author zlt
* @date 2019/8/5
*/
public class CustomUserAuthenticationConverter implements UserAuthenticationConverter {
private Collection<? extends GrantedAuthority> defaultAuthorities;
private UserDetailsService userDetailsService;
/**
* Optional {@link UserDetailsService} to use when extracting an {@link Authentication} from the incoming map.
*
* @param userDetailsService the userDetailsService to set
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
/**
* Default value for authorities if an Authentication is being created and the input has no data for authorities.
* Note that unless this property is set, the default Authentication created by {@link #extractAuthentication(Map)}
* will be unauthenticated.
*
* @param defaultAuthorities the defaultAuthorities to set. Default null.
*/
public void setDefaultAuthorities(String[] defaultAuthorities) {
this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.arrayToCommaDelimitedString(defaultAuthorities));
}
@Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put(USERNAME, authentication.getName());
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
return response;
}
@Override
public Authentication extractAuthentication(Map<String, ?> map) {
if (map.containsKey(USERNAME)) {
Object principal = map.get(USERNAME);
Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
if (userDetailsService != null) {
UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME));
authorities = user.getAuthorities();
principal = user;
} else {
Integer id = (Integer)map.get("id");
LoginAppUser user = new LoginAppUser();
user.setUsername((String)principal);
user.setId(Long.valueOf(id));
principal = user;
}
return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
}
return null;
}
private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
if (!map.containsKey(AUTHORITIES)) {
return defaultAuthorities;
}
Object authorities = map.get(AUTHORITIES);
if (authorities instanceof String) {
return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
}
if (authorities instanceof Collection) {
return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
.collectionToCommaDelimitedString((Collection<?>) authorities));
}
throw new IllegalArgumentException("Authorities must be either a String or a Collection");
}
}
@@ -0,0 +1,17 @@
package com.central.oauth2.common.exception;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
* @author: zlt
* @date: 2023/11/16
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomOAuth2AuthenticationException extends OAuth2AuthenticationException {
public CustomOAuth2AuthenticationException(String msg) {
super(new OAuth2Error(msg), msg);
}
}
@@ -1,44 +0,0 @@
package com.central.oauth2.common.service.impl;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* 自定义 TokenExtractor
*
* @author zlt
* @version 1.0
* @date 2022/6/4
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(HttpServletRequest.class)
@Component
public class CustomBearerTokenExtractor extends BearerTokenExtractor {
@Resource
private SecurityProperties securityProperties;
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
/**
* 解决只要请求携带access_token,排除鉴权的url依然会被拦截
*/
@Override
public Authentication extract(HttpServletRequest request) {
//判断当前请求为排除鉴权的url时,直接返回null
for (String url : securityProperties.getIgnore().getUrls()) {
if (antPathMatcher.match(url, request.getRequestURI())) {
return null;
}
}
return super.extract(request);
}
}
@@ -0,0 +1,112 @@
package com.central.oauth2.common.service.impl;
import com.central.oauth2.common.properties.PermitProperties;
import com.central.oauth2.common.properties.SecurityProperties;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrors;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author: zlt
* @date: 2023/11/8
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@ConditionalOnClass(HttpServletRequest.class)
@Component
public class CustomBearerTokenResolver implements BearerTokenResolver {
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private final boolean allowFormEncodedBodyParameter = false;
private final boolean allowUriQueryParameter = true;
private final String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
private final PathMatcher pathMatcher = new AntPathMatcher();
private final PermitProperties permitProperties;
public CustomBearerTokenResolver(SecurityProperties securityProperties) {
this.permitProperties = securityProperties.getIgnore();
}
@Override
public String resolve(HttpServletRequest request) {
boolean match = Arrays.stream(permitProperties.getUrls())
.anyMatch(url -> pathMatcher.match(url, request.getRequestURI()));
if (match) {
return null;
}
final String authorizationHeaderToken = resolveFromAuthorizationHeader(request);
final String parameterToken = isParameterTokenSupportedForRequest(request)
? resolveFromRequestParameters(request) : null;
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
final BearerTokenError error = BearerTokenErrors
.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken;
}
if (parameterToken != null && isParameterTokenEnabledForRequest(request)) {
return parameterToken;
}
return null;
}
private String resolveFromAuthorizationHeader(HttpServletRequest request) {
String authorization = request.getHeader(this.bearerTokenHeaderName);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (!matcher.matches()) {
BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed");
throw new OAuth2AuthenticationException(error);
}
return matcher.group("token");
}
private static String resolveFromRequestParameters(HttpServletRequest request) {
String[] values = request.getParameterValues("access_token");
if (values == null || values.length == 0) {
return null;
}
if (values.length == 1) {
return values[0];
}
BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
private boolean isParameterTokenSupportedForRequest(final HttpServletRequest request) {
return (("POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| "GET".equals(request.getMethod()));
}
private boolean isParameterTokenEnabledForRequest(final HttpServletRequest request) {
return ((this.allowFormEncodedBodyParameter && "POST".equals(request.getMethod())
&& MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()))
|| (this.allowUriQueryParameter && "GET".equals(request.getMethod())));
}
}
@@ -1,120 +0,0 @@
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.context.TenantContextHolder;
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.provider.OAuth2Authentication;
import org.springframework.util.AntPathMatcher;
import java.util.List;
import java.util.stream.Collectors;
/**
* 请求权限判断service
*
* @author zlt
* @date 2018/10/28
* <p>
* Blog: http://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<SysMenu> 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;
}
//超级管理员admin不需认证
String username = AuthUtils.getUsername(authentication);
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
return true;
}
OAuth2Authentication auth2Authentication = (OAuth2Authentication)authentication;
//判断应用黑白名单
if (!isNeedAuth(auth2Authentication.getOAuth2Request().getClientId())) {
return true;
}
//判断不进行url权限认证的api,所有已登录用户都能访问的url
for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) {
if (antPathMatcher.match(path, requestURI)) {
return true;
}
}
List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
log.warn("角色列表为空:{}", authentication.getPrincipal());
return false;
}
//保存租户信息
String clientId = auth2Authentication.getOAuth2Request().getClientId();
TenantContextHolder.setTenant(clientId);
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
List<SysMenu> 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<String> includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds();
//黑名单
List<String> exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds();
if (includeClientIds.size() > 0) {
result = includeClientIds.contains(clientId);
} else if(exclusiveClientIds.size() > 0) {
result = !exclusiveClientIds.contains(clientId);
}
return result;
}
}
@@ -1,28 +0,0 @@
package com.central.oauth2.common.store;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
/**
* 认证服务器使用数据库存取令牌
*
* @author zlt
* @date 2018/7/24 16:23
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "db")
public class AuthDbTokenStore {
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore(){
return new JdbcTokenStore(dataSource);
}
}
@@ -1,55 +0,0 @@
package com.central.oauth2.common.store;
import com.central.common.model.SysUser;
import com.central.oauth2.common.converter.CustomUserAuthenticationConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;
/**
* 认证服务器使用 JWT RSA 非对称加密令牌
*
* @author zlt
* @date 2018/7/24 16:21
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "authJwt")
public class AuthJwtTokenStore {
@Resource
private KeyProperties keyProperties;
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
@Order(2)
public JwtAccessTokenConverter jwtAccessTokenConverter() {
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory
(keyProperties.getKeyStore().getLocation(), keyProperties.getKeyStore().getSecret().toCharArray())
.getKeyPair(keyProperties.getKeyStore().getAlias());
converter.setKeyPair(keyPair);
DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter();
tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
return converter;
}
}
@@ -1,29 +0,0 @@
package com.central.oauth2.common.store;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.provider.token.TokenStore;
/**
* 认证服务器使用Redis存取令牌
* 注意: 需要配置redis参数
*
* @author zlt
* @date 2018/7/25 9:36
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "redis", matchIfMissing = true)
public class AuthRedisTokenStore {
@Bean
public TokenStore tokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer<Object> redisValueSerializer) {
return new CustomRedisTokenStore(connectionFactory, securityProperties, redisValueSerializer);
}
}
@@ -1,543 +0,0 @@
package com.central.oauth2.common.store;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.AuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* 优化自Spring Security的RedisTokenStore
* 1. 支持redis所有集群模式包括cluster模式
* 2. 使用pipeline减少连接次数,提升性能
* 3. 自动续签token(可配置是否开启)
*
* @author zlt
* @date 2019/7/7
*/
public class CustomRedisTokenStore implements TokenStore {
private static final String ACCESS = "access:";
private static final String ACCESS_BAK = "access_bak:";
private static final String AUTH_TO_ACCESS = "auth_to_access:";
private static final String REFRESH_AUTH = "refresh_auth:";
private static final String ACCESS_TO_REFRESH = "access_to_refresh:";
private static final String REFRESH = "refresh:";
private static final String REFRESH_TO_ACCESS = "refresh_to_access:";
private static final boolean springDataRedis_2_0 = ClassUtils.isPresent(
"org.springframework.data.redis.connection.RedisStandaloneConfiguration",
RedisTokenStore.class.getClassLoader());
private final RedisConnectionFactory connectionFactory;
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
private RedisTokenStoreSerializationStrategy serializationStrategy = new JdkSerializationStrategy();
private String prefix = "";
private Method redisConnectionSet_2_0;
/**
* 认证配置
*/
private SecurityProperties securityProperties;
/**
* 业务redis的value序列化
*/
private RedisSerializer<Object> redisValueSerializer;
public CustomRedisTokenStore(RedisConnectionFactory connectionFactory, SecurityProperties securityProperties, RedisSerializer<Object> redisValueSerializer) {
this.connectionFactory = connectionFactory;
this.securityProperties = securityProperties;
this.redisValueSerializer = redisValueSerializer;
if (springDataRedis_2_0) {
this.loadRedisConnectionMethods_2_0();
}
}
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
public void setSerializationStrategy(RedisTokenStoreSerializationStrategy serializationStrategy) {
this.serializationStrategy = serializationStrategy;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
private void loadRedisConnectionMethods_2_0() {
this.redisConnectionSet_2_0 = ReflectionUtils.findMethod(
RedisConnection.class, "set", byte[].class, byte[].class);
}
private RedisConnection getConnection() {
return connectionFactory.getConnection();
}
private byte[] serialize(Object object) {
return serializationStrategy.serialize(object);
}
private byte[] serializeKey(String object) {
return serialize(prefix + object);
}
private OAuth2AccessToken deserializeAccessToken(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2AccessToken.class);
}
private OAuth2Authentication deserializeAuthentication(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2Authentication.class);
}
private OAuth2RefreshToken deserializeRefreshToken(byte[] bytes) {
return serializationStrategy.deserialize(bytes, OAuth2RefreshToken.class);
}
private ClientDetails deserializeClientDetails(byte[] bytes) {
return (ClientDetails) redisValueSerializer.deserialize(bytes);
}
private byte[] serialize(String string) {
return serializationStrategy.serialize(string);
}
private String deserializeString(byte[] bytes) {
return serializationStrategy.deserializeString(bytes);
}
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(serializedKey);
} finally {
conn.close();
}
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
if (accessToken != null) {
OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
// Keep the stores consistent (maybe the same user is
// represented by this authentication but the details have
// changed)
storeAccessToken(accessToken, authentication);
}
}
return accessToken;
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
OAuth2Authentication auth2Authentication = readAuthentication(token.getValue());
//是否开启token续签
boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
if (isRenew && auth2Authentication != null) {
OAuth2Request clientAuth = auth2Authentication.getOAuth2Request();
//判断当前应用是否需要自动续签
if (checkRenewClientId(clientAuth.getClientId())) {
//获取过期时长
int validitySeconds = getAccessTokenValiditySeconds(clientAuth.getClientId());
if (validitySeconds > 0) {
double expiresRatio = token.getExpiresIn() / (double) validitySeconds;
//判断是否需要续签,当前剩余时间小于过期时长的50%则续签
if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
//更新AccessToken过期时间
DefaultOAuth2AccessToken oAuth2AccessToken = (DefaultOAuth2AccessToken) token;
oAuth2AccessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
storeAccessToken(oAuth2AccessToken, auth2Authentication, true);
}
}
}
}
return auth2Authentication;
}
/**
* 判断应用自动续签是否满足白名单和黑名单的过滤逻辑
*
* @param clientId 应用id
* @return 是否满足
*/
private boolean checkRenewClientId(String clientId) {
boolean result = true;
//白名单
List<String> includeClientIds = securityProperties.getAuth().getRenew().getIncludeClientIds();
//黑名单
List<String> 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 int getAccessTokenValiditySeconds(String clientId) {
RedisConnection conn = getConnection();
byte[] bytes;
try {
bytes = conn.get(serializeKey(SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId));
} finally {
conn.close();
}
if (bytes != null) {
ClientDetails clientDetails = deserializeClientDetails(bytes);
if (clientDetails.getAccessTokenValiditySeconds() != null) {
return clientDetails.getAccessTokenValiditySeconds();
}
}
//返回默认值
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
}
@Override
public OAuth2Authentication readAuthentication(String token) {
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token));
} finally {
conn.close();
}
return deserializeAuthentication(bytes);
}
@Override
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
public OAuth2Authentication readAuthenticationForRefreshToken(String token) {
RedisConnection conn = getConnection();
try {
byte[] bytes = conn.get(serializeKey(REFRESH_AUTH + token));
return deserializeAuthentication(bytes);
} finally {
conn.close();
}
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
storeAccessToken(token, authentication, false);
}
/**
* 存储token
*
* @param isRenew 是否续签
*/
private void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication, boolean isRenew) {
byte[] serializedAccessToken = serialize(token);
byte[] serializedAuth = serialize(authentication);
byte[] accessKey = serializeKey(ACCESS + token.getValue());
byte[] accessBakKey = serializeKey(ACCESS_BAK + token.getValue());
byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + token.getValue());
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
RedisConnection conn = getConnection();
try {
byte[] oldAccessToken = conn.get(accessKey);
//如果token已存在,并且不是续签的话直接返回
if (!isRenew && oldAccessToken != null) {
return;
}
conn.openPipeline();
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
this.redisConnectionSet_2_0.invoke(conn, accessBakKey, serializedAccessToken);
this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(accessKey, serializedAccessToken);
conn.set(accessBakKey, serializedAccessToken);
conn.set(authKey, serializedAuth);
conn.set(authToAccessKey, serializedAccessToken);
}
//如果是续签token,需要先删除集合里旧的值
if (oldAccessToken != null) {
if (!authentication.isClientOnly()) {
conn.lRem(approvalKey, 1, oldAccessToken);
}
conn.lRem(clientId, 1, oldAccessToken);
}
if (!authentication.isClientOnly()) {
conn.rPush(approvalKey, serializedAccessToken);
}
conn.rPush(clientId, serializedAccessToken);
if (token.getExpiration() != null) {
int seconds = token.getExpiresIn();
conn.expire(accessKey, seconds);
conn.expire(accessBakKey, seconds + 60);
conn.expire(authKey, seconds);
conn.expire(authToAccessKey, seconds);
conn.expire(clientId, seconds);
conn.expire(approvalKey, seconds);
}
OAuth2RefreshToken refreshToken = token.getRefreshToken();
if (refreshToken != null && refreshToken.getValue() != null) {
byte[] refresh = serialize(token.getRefreshToken().getValue());
byte[] auth = serialize(token.getValue());
byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(refreshToAccessKey, auth);
conn.set(accessToRefreshKey, refresh);
}
expireRefreshToken(refreshToken, conn, refreshToAccessKey, accessToRefreshKey);
}
conn.closePipeline();
} finally {
conn.close();
}
}
private static String getApprovalKey(OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication() == null ? ""
: authentication.getUserAuthentication().getName();
return getApprovalKey(authentication.getOAuth2Request().getClientId(), userName);
}
private static String getApprovalKey(String clientId, String userName) {
return clientId + (userName == null ? "" : ":" + userName);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
removeAccessToken(accessToken.getValue());
}
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
byte[] key = serializeKey(ACCESS + tokenValue);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
return deserializeAccessToken(bytes);
}
public void removeAccessToken(String tokenValue) {
byte[] accessKey = serializeKey(ACCESS + tokenValue);
byte[] accessBakKey = serializeKey(ACCESS_BAK + tokenValue);
byte[] authKey = serializeKey(SecurityConstants.REDIS_TOKEN_AUTH + tokenValue);
byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
byte[] access = conn.get(accessKey);
byte[] auth = conn.get(authKey);
conn.openPipeline();
conn.del(accessKey);
conn.del(accessBakKey);
conn.del(accessToRefreshKey);
// Don't remove the refresh token - it's up to the caller to do that
conn.del(authKey);
conn.closePipeline();
OAuth2Authentication authentication = deserializeAuthentication(auth);
if (authentication != null) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] unameKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(authentication));
byte[] clientId = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
conn.openPipeline();
conn.del(authToAccessKey);
conn.lRem(unameKey, 1, access);
conn.lRem(clientId, 1, access);
conn.del(serialize(ACCESS + key));
conn.closePipeline();
}
} finally {
conn.close();
}
}
@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
byte[] serializedRefreshToken = serialize(refreshToken);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
if (springDataRedis_2_0) {
try {
this.redisConnectionSet_2_0.invoke(conn, refreshKey, serializedRefreshToken);
this.redisConnectionSet_2_0.invoke(conn, refreshAuthKey, serialize(authentication));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
} else {
conn.set(refreshKey, serializedRefreshToken);
conn.set(refreshAuthKey, serialize(authentication));
}
expireRefreshToken(refreshToken, conn, refreshKey, refreshAuthKey);
conn.closePipeline();
} finally {
conn.close();
}
}
private void expireRefreshToken(OAuth2RefreshToken refreshToken, RedisConnection conn, byte[] refreshKey, byte[] refreshAuthKey) {
if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
Date expiration = expiringRefreshToken.getExpiration();
if (expiration != null) {
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L)
.intValue();
conn.expire(refreshKey, seconds);
conn.expire(refreshAuthKey, seconds);
}
}
}
@Override
public OAuth2RefreshToken readRefreshToken(String tokenValue) {
byte[] key = serializeKey(REFRESH + tokenValue);
byte[] bytes;
RedisConnection conn = getConnection();
try {
bytes = conn.get(key);
} finally {
conn.close();
}
return deserializeRefreshToken(bytes);
}
@Override
public void removeRefreshToken(OAuth2RefreshToken refreshToken) {
removeRefreshToken(refreshToken.getValue());
}
public void removeRefreshToken(String tokenValue) {
byte[] refreshKey = serializeKey(REFRESH + tokenValue);
byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + tokenValue);
byte[] refresh2AccessKey = serializeKey(REFRESH_TO_ACCESS + tokenValue);
byte[] access2RefreshKey = serializeKey(ACCESS_TO_REFRESH + tokenValue);
RedisConnection conn = getConnection();
try {
conn.openPipeline();
conn.del(refreshKey);
conn.del(refreshAuthKey);
conn.del(refresh2AccessKey);
conn.del(access2RefreshKey);
conn.closePipeline();
} finally {
conn.close();
}
}
@Override
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
}
private void removeAccessTokenUsingRefreshToken(String refreshToken) {
byte[] key = serializeKey(REFRESH_TO_ACCESS + refreshToken);
RedisConnection conn = getConnection();
byte[] bytes = null;
try {
bytes = conn.get(key);
conn.del(key);
} finally {
conn.close();
}
if (bytes == null) {
return;
}
String accessToken = deserializeString(bytes);
if (accessToken != null) {
removeAccessToken(accessToken);
}
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
byte[] approvalKey = serializeKey(SecurityConstants.REDIS_UNAME_TO_ACCESS + getApprovalKey(clientId, userName));
List<byte[]> byteList;
RedisConnection conn = getConnection();
try {
byteList = conn.lRange(approvalKey, 0, -1);
} finally {
conn.close();
}
return getTokenCollections(byteList);
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
byte[] key = serializeKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS + clientId);
List<byte[]> byteList;
RedisConnection conn = getConnection();
try {
byteList = conn.lRange(key, 0, -1);
} finally {
conn.close();
}
return getTokenCollections(byteList);
}
private Collection<OAuth2AccessToken> getTokenCollections(List<byte[]> byteList) {
if (byteList == null || byteList.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size());
for (byte[] bytes : byteList) {
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
}
}
@@ -1,89 +0,0 @@
package com.central.oauth2.common.store;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.SecurityConstants;
import com.central.oauth2.common.converter.CustomUserAuthenticationConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Base64;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 资源服务器 TokenStore 配置类,使用 JWT RSA 非对称加密
*
* @author zlt
* @date 2018/8/20 9:25
*/
@Configuration
@ConditionalOnProperty(prefix = "zlt.oauth2.token.store", name = "type", havingValue = "resJwt")
public class ResJwtTokenStore {
@Autowired
private ResourceServerProperties resource;
@Bean
public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
DefaultAccessTokenConverter tokenConverter = (DefaultAccessTokenConverter)converter.getAccessTokenConverter();
tokenConverter.setUserTokenConverter(new CustomUserAuthenticationConverter());
return converter;
}
/**
* 获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getPubKey() {
Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
return getKeyFromAuthorizationServer();
}
}
/**
* 通过访问授权服务器获取非对称加密公钥 Key
* @return 公钥 Key
*/
private String getKeyFromAuthorizationServer() {
if (StrUtil.isNotEmpty(this.resource.getJwt().getKeyUri())) {
final HttpHeaders headers = new HttpHeaders();
final String username = this.resource.getClientId();
final String password = this.resource.getClientSecret();
if (username != null && password != null) {
final byte[] token = Base64.getEncoder().encode((username + ":" + password).getBytes());
headers.add("Authorization", "Basic " + new String(token));
}
final HttpEntity<Void> request = new HttpEntity<>(headers);
final String url = this.resource.getJwt().getKeyUri();
return (String) new RestTemplate()
.exchange(url, HttpMethod.GET, request, Map.class).getBody()
.get("value");
}
return null;
}
}
@@ -0,0 +1,66 @@
package com.central.oauth2.common.token;
import lombok.Getter;
import lombok.Setter;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.server.authorization.util.SpringAuthorizationServerVersion;
import java.io.Serial;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* @author: zlt
* @date: 2023/11/15
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Getter
@Setter
public class BaseAuthenticationToken extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = SpringAuthorizationServerVersion.SERIAL_VERSION_UID;
private final AuthorizationGrantType grantType;
private Authentication clientPrincipal;
private Map<String, Object> additionalParameters;
private Set<String> scopes;
public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType) {
super(null);
this.grantType = authorizationGrantType;
}
public BaseAuthenticationToken(AuthorizationGrantType authorizationGrantType, Set<String> scopes
, Authentication clientPrincipal, @Nullable Map<String, Object> additionalParameters) {
super(null);
this.grantType = authorizationGrantType;
this.scopes = Collections.unmodifiableSet(scopes != null ? scopes : Collections.emptySet());
this.clientPrincipal = clientPrincipal;
this.additionalParameters = additionalParameters;
}
public BaseAuthenticationToken(Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.grantType = null;
this.clientPrincipal = null;
this.additionalParameters = null;
this.scopes = null;
}
@Override
public Object getPrincipal() {
return this.clientPrincipal;
}
@Override
public Object getCredentials() {
return "";
}
}
@@ -0,0 +1,19 @@
package com.central.oauth2.common.token;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import java.util.Map;
/**
* @author: zlt
* @date: 2023/11/20
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomAccessToken extends OAuth2Authorization.Token<OAuth2AccessToken> {
protected CustomAccessToken(OAuth2AccessToken token, Map metadata) {
super(token, metadata);
}
}
@@ -1,22 +1,24 @@
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.utils.SpringUtil;
import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
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.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
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 java.nio.charset.StandardCharsets;
import java.util.*;
@@ -45,7 +47,7 @@ public class AuthUtils {
public static String extractToken(HttpServletRequest request) {
String token = extractHeaderToken(request);
if (token == null) {
token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
token = request.getParameter(OAuth2ParameterNames.ACCESS_TOKEN);
if (token == null) {
log.debug("Token not found in request parameters. Not an OAuth2 request.");
}
@@ -62,8 +64,8 @@ public class AuthUtils {
Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
while (headers.hasMoreElements()) {
String value = headers.nextElement();
if ((value.startsWith(OAuth2AccessToken.BEARER_TYPE))) {
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
if ((value.startsWith(OAuth2AccessToken.TokenType.BEARER.getValue()))) {
String authHeaderValue = value.substring(OAuth2AccessToken.TokenType.BEARER.getValue().length()).trim();
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
@@ -83,19 +85,20 @@ public class AuthUtils {
}
public static SysUser checkAccessToken(String accessTokenValue) {
TokenStore tokenStore = SpringUtil.getBean(TokenStore.class);
OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
if (accessToken == null || accessToken.getValue() == null) {
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
} else if (accessToken.isExpired()) {
tokenStore.removeAccessToken(accessToken);
throw new InvalidTokenException("Access token expired: " + 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);
}
OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
/*OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
if (result == null) {
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
}
return setContext(result);
throw new OAuth2AuthenticationException("Invalid access token: " + accessTokenValue);
}*/
// TODO 如何生成 Authentication 对象
return setContext(null);
}
/**
@@ -114,11 +117,20 @@ public class AuthUtils {
public static String[] extractClient(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
throw new CustomOAuth2AuthenticationException("The client information in the request header is empty");
}
return extractHeaderClient(header);
}
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");
}
String[] clientArr = extractHeaderClient(header);
return clientArr[0];
}
/**
* 从header 请求中的clientId:clientSecret
*
@@ -130,7 +142,7 @@ public class AuthUtils {
String clientStr = new String(decoded, StandardCharsets.UTF_8);
String[] clientArr = clientStr.split(":");
if (clientArr.length != 2) {
throw new RuntimeException("Invalid basic authentication token");
throw new CustomOAuth2AuthenticationException("Invalid basic authentication token");
}
return clientArr;
}
@@ -170,17 +182,8 @@ public class AuthUtils {
public static String getAccountType(Authentication authentication) {
String accountType = null;
if (authentication != null) {
Object details = authentication.getDetails();
if (details != null) {
if (details instanceof CustomWebAuthenticationDetails) {
CustomWebAuthenticationDetails detailsObj = (CustomWebAuthenticationDetails) details;
accountType = detailsObj.getAccountType();
} else {
Map<String, String> detailsMap = (Map<String, String>) details;
if (detailsMap != null) {
accountType = detailsMap.get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
}
}
if (authentication instanceof BaseAuthenticationToken authenticationToken) {
accountType = (String)authenticationToken.getAdditionalParameters().get(SecurityConstants.ACCOUNT_TYPE_PARAM_NAME);
}
}
return accountType;
@@ -1,108 +0,0 @@
package com.central.oauth2.common.util;
import com.central.common.constant.SecurityConstants;
import com.central.common.utils.JsonUtil;
import com.central.common.utils.RsaUtils;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.SignatureVerifier;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.stream.Collectors;
/**
* jwt工具类
*
* @author zlt
* @date 2019/7/21
*/
public class JwtUtils {
private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----";
private static final String PUBKEY_END = "-----END PUBLIC KEY-----";
/**
* 通过classpath获取公钥值
*/
public static RSAPublicKey getPubKeyObj() {
Resource res = new ClassPathResource(SecurityConstants.RSA_PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
String pubKey = br.lines().collect(Collectors.joining("\n"));
pubKey = pubKey.substring(PUBKEY_START.length(), pubKey.indexOf(PUBKEY_END));
return RsaUtils.getPublicKey(pubKey);
} catch (Exception ioe) {
ioe.printStackTrace();
}
return null;
}
/**
* {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
* @param jwtToken token值
* @param rsaPublicKey 公钥
* @return
*/
public static JsonNode decodeAndVerify(String jwtToken, RSAPublicKey rsaPublicKey) {
SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey);
Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
return JsonUtil.parse(jwt.getClaims());
}
/**
* {"exp":1563256084,"user_name":"admin","authorities":["ADMIN"],"jti":"4ce02f54-3d1c-4461-8af1-73f0841a35df","client_id":"webApp","scope":["app"]}
* @param jwtToken token值
* @return
*/
public static JsonNode decodeAndVerify(String jwtToken) {
return decodeAndVerify(jwtToken, getPubKeyObj());
}
/**
* 判断jwt是否过期
* @param claims jwt内容
* @param currTime 当前时间
* @return 未过期:true,已过期:false
*/
public static boolean checkExp(JsonNode claims, long currTime) {
long exp = claims.get("exp").asLong();
if (exp < currTime) {
return false;
}
return true;
}
/**
* 判断jwt是否过期
* @param claims jwt内容
* @return 未过期:true,已过期:false
*/
public static boolean checkExp(JsonNode claims) {
return checkExp(claims, System.currentTimeMillis());
}
public static Jwt encode(CharSequence content, KeyProperties keyProperties) {
KeyPair keyPair = new KeyStoreKeyFactory(
keyProperties.getKeyStore().getLocation(),
keyProperties.getKeyStore().getSecret().toCharArray())
.getKeyPair(keyProperties.getKeyStore().getAlias());
PrivateKey privateKey = keyPair.getPrivate();
Signer rsaSigner = new RsaSigner((RSAPrivateKey) privateKey);
return JwtHelper.encode(content, rsaSigner);
}
public static String encodeStr(CharSequence content, KeyProperties keyProperties) {
return encode(content, keyProperties).getEncoded();
}
}