feat: gateway增加统一鉴权功能
This commit is contained in:
+1
-2
@@ -1,7 +1,6 @@
|
||||
package com.central.oauth2.common;
|
||||
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.properties.TokenStoreProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@@ -15,7 +14,7 @@ import org.springframework.context.annotation.ComponentScan;
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@EnableConfigurationProperties({SecurityProperties.class, TokenStoreProperties.class})
|
||||
@EnableConfigurationProperties({SecurityProperties.class})
|
||||
@ComponentScan
|
||||
public class AuthClientAutoConfiguration {
|
||||
}
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.central.oauth2.common.component;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @version 1.0
|
||||
* @date 2023/12/4
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
public class CustomReactiveAuthorizationServiceIntrospector implements ReactiveOpaqueTokenIntrospector {
|
||||
@Override
|
||||
public Mono<OAuth2AuthenticatedPrincipal> introspect(String accessTokenValue) {
|
||||
return Mono.just(accessTokenValue)
|
||||
.map(AuthUtils::checkAccessTokenToAuth)
|
||||
.map(this::convertClaimsSet)
|
||||
.onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError);
|
||||
}
|
||||
|
||||
private OAuth2AuthenticatedPrincipal convertClaimsSet(OAuth2Authorization authorization) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
Collection<GrantedAuthority> authorities = new ArrayList<>();
|
||||
|
||||
claims.put(SecurityConstants.CLIENT_ID, authorization.getRegisteredClientId());
|
||||
claims.putAll(authorization.getAttributes());
|
||||
|
||||
Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName());
|
||||
if (authentication != null) {
|
||||
authorities.addAll(authentication.getAuthorities());
|
||||
}
|
||||
|
||||
return new OAuth2IntrospectionAuthenticatedPrincipal(authorization.getPrincipalName(), claims, authorities);
|
||||
}
|
||||
|
||||
private OAuth2IntrospectionException onError(Throwable ex) {
|
||||
return new OAuth2IntrospectionException(ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.central.oauth2.common.config;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.utils.ResponseUtil;
|
||||
import com.central.common.utils.WebfluxResponseUtil;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.service.impl.RedisOAuth2AuthorizationService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
|
||||
import com.nimbusds.jose.jwk.source.JWKSource;
|
||||
import com.nimbusds.jose.proc.SecurityContext;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.redisson.api.RBucket;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.jwt.JwtEncoder;
|
||||
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
|
||||
import org.springframework.web.server.ServerWebExchange;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.text.ParseException;
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @date: 2023/11/25
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
public class BaseSecurityConfig {
|
||||
@Bean
|
||||
public OAuth2AuthorizationService oAuth2AuthorizationService(SecurityProperties securityProperties, RedissonClient redisson) {
|
||||
return new RedisOAuth2AuthorizationService(securityProperties, redisson);
|
||||
}
|
||||
|
||||
/**
|
||||
* 鉴权错误处理
|
||||
*/
|
||||
@Bean
|
||||
public AuthenticationEntryPoint authenticationEntryPoint(ObjectMapper objectMapper) {
|
||||
return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
|
||||
}
|
||||
@Bean
|
||||
public ServerAuthenticationEntryPoint serverAuthenticationEntryPoint() {
|
||||
return (exchange, e) -> WebfluxResponseUtil.responseFailed(exchange, HttpStatus.UNAUTHORIZED.value(), e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 越权错误处理
|
||||
*/
|
||||
@Bean
|
||||
public AccessDeniedHandler oAuth2AccessDeniedHandler(ObjectMapper objectMapper) {
|
||||
return (request, response, authException) -> ResponseUtil.responseFailed(objectMapper, response, authException.getMessage());
|
||||
}
|
||||
@Bean
|
||||
public ServerAccessDeniedHandler serverAccessDeniedHandler() {
|
||||
return (exchange, e) -> WebfluxResponseUtil.responseFailed(exchange, HttpStatus.FORBIDDEN.value(), e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置jwk源,使用非对称加密,公开用于检索匹配指定选择器的JWK的方法
|
||||
*/
|
||||
@Bean
|
||||
public JWKSource<SecurityContext> jwkSource(RedissonClient redisson) throws ParseException {
|
||||
RBucket<String> rBucket = redisson.getBucket(SecurityConstants.AUTHORIZATION_JWS_PREFIX_KEY);
|
||||
String jwkSetCache = rBucket.get();
|
||||
JWKSet jwkSet;
|
||||
// 多个服务共用同一个 jwkSource 对象
|
||||
if (StrUtil.isEmpty(jwkSetCache)) {
|
||||
KeyPair keyPair = generateRsaKey();
|
||||
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
|
||||
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
|
||||
RSAKey rsaKey = new RSAKey.Builder(publicKey)
|
||||
.privateKey(privateKey)
|
||||
.keyID(UUID.randomUUID().toString())
|
||||
.build();
|
||||
jwkSet = new JWKSet(rsaKey);
|
||||
String jwkSetString = jwkSet.toString(Boolean.FALSE);
|
||||
// 缓存
|
||||
boolean success = rBucket.setIfAbsent(jwkSetString);
|
||||
if (!success) {// 防止同时启动服务时创建了多个jwks
|
||||
jwkSetCache = rBucket.get();
|
||||
jwkSet = JWKSet.parse(jwkSetCache);
|
||||
}
|
||||
} else {
|
||||
// 解析存储的jws
|
||||
jwkSet = JWKSet.parse(jwkSetCache);
|
||||
}
|
||||
return new ImmutableJWKSet<>(jwkSet);
|
||||
}
|
||||
|
||||
private static KeyPair generateRsaKey() {
|
||||
KeyPair keyPair;
|
||||
try {
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(2048);
|
||||
keyPair = keyPairGenerator.generateKeyPair();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
return keyPair;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
|
||||
return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
|
||||
return new NimbusJwtEncoder(jwkSource);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.central.oauth2.common.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
* @version 1.0
|
||||
* @date 2023/12/2
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Data
|
||||
public class ClientDto implements Serializable {
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
private String clientId;
|
||||
/**
|
||||
* 应用名称
|
||||
*/
|
||||
private String clientName;
|
||||
private String resourceIds = "";
|
||||
private String clientSecret;
|
||||
private String clientSecretStr;
|
||||
private String scope = "all";
|
||||
private String authorizedGrantTypes = "authorization_code,password,refresh_token,client_credentials";
|
||||
private String webServerRedirectUri;
|
||||
private String authorities = "";
|
||||
|
||||
private Integer accessTokenValiditySeconds = 18000;
|
||||
|
||||
private Integer refreshTokenValiditySeconds = 28800;
|
||||
private String additionalInformation = "{}";
|
||||
private String autoapprove = "true";
|
||||
/**
|
||||
* 是否支持id_token
|
||||
*/
|
||||
private Boolean supportIdToken = true;
|
||||
/**
|
||||
* id_token有效时间(s)
|
||||
*/
|
||||
private Integer idTokenValiditySeconds = 60;
|
||||
|
||||
private Long creatorId;
|
||||
}
|
||||
+5
-9
@@ -23,15 +23,11 @@ public class PermitProperties {
|
||||
* 监控中心和swagger需要访问的url
|
||||
*/
|
||||
private static final String[] ENDPOINTS = {
|
||||
"/oauth/**",
|
||||
"/actuator/**",
|
||||
"/*/v2/api-docs",
|
||||
"/swagger/api-docs",
|
||||
"/swagger-ui.html",
|
||||
"/doc.html",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/druid/**"
|
||||
"/login.html", "/validata/code/**",
|
||||
"/v3/api-docs/**", "/*/v3/api-docs/**",
|
||||
"/doc.html", "/swagger-ui.html", "/swagger-ui/**",
|
||||
"/actuator/**", "/webjars/**", "/druid/**",
|
||||
"/css/**", "/js/**", "/images/**", "/favicon.ico", "/error",
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 资源服务器配置
|
||||
*
|
||||
* @author: zlt
|
||||
* @date: 2023/11/26
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
public class ResourceServerProperties {
|
||||
/**
|
||||
* token格式: reference 引用令牌(不透明), self-contained 自包含令牌(jwt))
|
||||
*/
|
||||
private String tokenFormat = "reference";
|
||||
}
|
||||
+2
@@ -23,4 +23,6 @@ public class SecurityProperties {
|
||||
private PermitProperties ignore = new PermitProperties();
|
||||
|
||||
private ValidateCodeProperties code = new ValidateCodeProperties();
|
||||
|
||||
private ResourceServerProperties resourceServer = new ResourceServerProperties();
|
||||
}
|
||||
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package com.central.oauth2.common.properties;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
|
||||
/**
|
||||
* Token配置
|
||||
*
|
||||
* @author zlt
|
||||
* @version 1.0
|
||||
* @date 2021/5/19
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@ConfigurationProperties(prefix = "zlt.oauth2.token.store")
|
||||
@RefreshScope
|
||||
public class TokenStoreProperties {
|
||||
/**
|
||||
* token存储类型(redis/db/authJwt/resJwt)
|
||||
*/
|
||||
private String type = "redis";
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.central.oauth2.common.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.model.SysMenu;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.util.AuthUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 请求权限判断service
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2018/10/28
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class DefaultPermissionServiceImpl {
|
||||
|
||||
@Autowired
|
||||
private SecurityProperties securityProperties;
|
||||
|
||||
private final AntPathMatcher antPathMatcher = new AntPathMatcher();
|
||||
|
||||
/**
|
||||
* 查询当前用户拥有的资源权限
|
||||
* @param roleCodes 角色code列表,多个以','隔开
|
||||
* @return
|
||||
*/
|
||||
public abstract List<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;
|
||||
}
|
||||
|
||||
OAuth2IntrospectionAuthenticatedPrincipal authenticatedPrincipal = (OAuth2IntrospectionAuthenticatedPrincipal)authentication.getPrincipal();
|
||||
//超级管理员admin不需认证
|
||||
String username = authenticatedPrincipal.getName();
|
||||
if (CommonConstant.ADMIN_USER_NAME.equals(username)) {
|
||||
return true;
|
||||
}
|
||||
Map<String, Object> claims = authenticatedPrincipal.getAttributes();
|
||||
String clientId = (String)claims.get(SecurityConstants.CLIENT_ID);
|
||||
//判断应用黑白名单
|
||||
if (!isNeedAuth(clientId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
//判断不进行url权限认证的api,所有已登录用户都能访问的url
|
||||
for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) {
|
||||
if (antPathMatcher.match(path, requestURI)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Collection<SimpleGrantedAuthority> grantedAuthorityList = (Collection<SimpleGrantedAuthority>) authentication.getAuthorities();
|
||||
if (CollectionUtil.isEmpty(grantedAuthorityList)) {
|
||||
log.warn("角色列表为空:{}", authentication.getPrincipal());
|
||||
return false;
|
||||
}
|
||||
|
||||
//保存租户信息
|
||||
TenantContextHolder.setTenant(clientId);
|
||||
|
||||
String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", "));
|
||||
List<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;
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
package com.central.oauth2.common.service.impl;
|
||||
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.oauth2.common.pojo.ClientDto;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import com.central.oauth2.common.token.CustomAccessToken;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.redisson.api.RBucket;
|
||||
import org.redisson.api.RList;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.redisson.codec.SerializationCodec;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
|
||||
import org.springframework.security.oauth2.core.OAuth2Token;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author: zlt
|
||||
* @date: 2023/11/9
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class RedisOAuth2AuthorizationService implements OAuth2AuthorizationService {
|
||||
private final static SerializationCodec AUTH_CODEC = new SerializationCodec();
|
||||
private final static Long TIMEOUT = 10L;
|
||||
|
||||
private static final String AUTHORIZATION = "token";
|
||||
|
||||
private final SecurityProperties securityProperties;
|
||||
|
||||
private final RedissonClient redisson;
|
||||
|
||||
@Override
|
||||
public void save(OAuth2Authorization authorization) {
|
||||
if (isState(authorization)) {
|
||||
String token = authorization.getAttribute("state");
|
||||
this.redisBucketSet(OAuth2ParameterNames.STATE, token, authorization, Duration.ofMinutes(TIMEOUT));
|
||||
}
|
||||
|
||||
if (isCode(authorization)) {
|
||||
OAuth2AuthorizationCode authorizationCode = authorization.getToken(OAuth2AuthorizationCode.class).getToken();
|
||||
Duration duration = this.getExpireSeconds(authorizationCode);
|
||||
this.redisBucketSet(OAuth2ParameterNames.CODE, authorizationCode.getTokenValue(), authorization, duration);
|
||||
}
|
||||
|
||||
if (isRefreshToken(authorization)) {
|
||||
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
|
||||
Duration duration = this.getExpireSeconds(refreshToken);
|
||||
this.redisBucketSet(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue(), authorization, duration);
|
||||
}
|
||||
|
||||
if (isAccessToken(authorization)) {
|
||||
Duration duration = this.saveAccessToken(authorization);
|
||||
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
|
||||
// 应用id集合
|
||||
this.redisListAdd(this.getClientIdListKey(authorization), accessToken.getTokenValue(), duration);
|
||||
// 应用id + 登录名 集合
|
||||
this.redisListAdd(this.getUnameListKey(authorization), accessToken.getTokenValue(), duration);
|
||||
}
|
||||
}
|
||||
|
||||
private Duration saveAccessToken(OAuth2Authorization authorization) {
|
||||
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
|
||||
Duration duration = this.getExpireSeconds(accessToken);
|
||||
this.redisBucketSet(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue(), authorization, duration);
|
||||
return duration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(OAuth2Authorization authorization) {
|
||||
Assert.notNull(authorization, "authorization cannot be null");
|
||||
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (isState(authorization)) {
|
||||
String token = authorization.getAttribute("state");
|
||||
keys.add(buildKey(OAuth2ParameterNames.STATE, token));
|
||||
}
|
||||
|
||||
if (isCode(authorization)) {
|
||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
|
||||
.getToken(OAuth2AuthorizationCode.class);
|
||||
OAuth2AuthorizationCode authorizationCodeToken = authorizationCode.getToken();
|
||||
keys.add(buildKey(OAuth2ParameterNames.CODE, authorizationCodeToken.getTokenValue()));
|
||||
}
|
||||
|
||||
if (isRefreshToken(authorization)) {
|
||||
OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken();
|
||||
keys.add(buildKey(OAuth2ParameterNames.REFRESH_TOKEN, refreshToken.getTokenValue()));
|
||||
}
|
||||
|
||||
if (isAccessToken(authorization)) {
|
||||
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
|
||||
keys.add(buildKey(OAuth2ParameterNames.ACCESS_TOKEN, accessToken.getTokenValue()));
|
||||
}
|
||||
redisson.getKeys().delete(keys.toArray(String[]::new));
|
||||
this.removeList(authorization);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public OAuth2Authorization findById(String id) {
|
||||
return this.findByToken(id, OAuth2TokenType.ACCESS_TOKEN);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public OAuth2Authorization findByToken(String token, @Nullable OAuth2TokenType tokenType) {
|
||||
Assert.hasText(token, "token cannot be empty");
|
||||
if (tokenType == null) {
|
||||
tokenType = OAuth2TokenType.ACCESS_TOKEN;
|
||||
}
|
||||
OAuth2Authorization authorization = this.redisBucketGet(tokenType.getValue(), token);
|
||||
|
||||
boolean isRenew = securityProperties.getAuth().getRenew().getEnable();
|
||||
if (isRenew && tokenType.equals(OAuth2TokenType.ACCESS_TOKEN) && authorization != null) {
|
||||
this.renew(authorization);
|
||||
}
|
||||
|
||||
return authorization;
|
||||
}
|
||||
|
||||
public void remove(String accessToken) {
|
||||
OAuth2Authorization oAuth2Authorization = this.findById(accessToken);
|
||||
this.remove(oAuth2Authorization);
|
||||
}
|
||||
|
||||
public List<String> findTokensByClientId(String clientId) {
|
||||
RList<String> rList = redisson.getList(this.getClientIdListKey(clientId));
|
||||
return rList.readAll();
|
||||
}
|
||||
|
||||
public List<String> findTokensByClientIdAndUserName(String clientId, String username) {
|
||||
RList<String> rList = redisson.getList(this.getUnameListKey(clientId, username));
|
||||
return rList.readAll();
|
||||
}
|
||||
|
||||
private String buildKey(String type, String id) {
|
||||
return String.format("%s::%s::%s", AUTHORIZATION, type, id);
|
||||
}
|
||||
|
||||
private static boolean isState(OAuth2Authorization authorization) {
|
||||
return Objects.nonNull(authorization.getAttribute("state"));
|
||||
}
|
||||
|
||||
private static boolean isCode(OAuth2Authorization authorization) {
|
||||
OAuth2Authorization.Token<OAuth2AuthorizationCode> authorizationCode = authorization
|
||||
.getToken(OAuth2AuthorizationCode.class);
|
||||
return Objects.nonNull(authorizationCode);
|
||||
}
|
||||
|
||||
private static boolean isRefreshToken(OAuth2Authorization authorization) {
|
||||
return Objects.nonNull(authorization.getRefreshToken());
|
||||
}
|
||||
|
||||
private static boolean isAccessToken(OAuth2Authorization authorization) {
|
||||
return Objects.nonNull(authorization.getAccessToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* 续签 access_token
|
||||
*/
|
||||
private void renew(OAuth2Authorization authorization) {
|
||||
// 判断当前应用是否需要自动续签
|
||||
if (checkRenewClientId(authorization.getRegisteredClientId())) {
|
||||
// 获取过期时长
|
||||
long validitySeconds = getAccessTokenValiditySeconds(authorization.getRegisteredClientId());
|
||||
if (validitySeconds > 0) {
|
||||
OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
|
||||
long expiresIn = ChronoUnit.SECONDS.between(Instant.now(), accessToken.getExpiresAt());
|
||||
double expiresRatio = expiresIn / (double) validitySeconds;
|
||||
// 判断是否需要续签,当前剩余时间小于过期时长的50%则续签
|
||||
if (expiresRatio <= securityProperties.getAuth().getRenew().getTimeRatio()) {
|
||||
// 更新AccessToken过期时间
|
||||
updateAccessTokenExpiresAt(authorization, validitySeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断应用自动续签是否满足白名单和黑名单的过滤逻辑
|
||||
*
|
||||
* @param clientId 应用id
|
||||
* @return 是否满足
|
||||
*/
|
||||
private boolean checkRenewClientId(String clientId) {
|
||||
boolean result = true;
|
||||
//白名单
|
||||
List<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 long getAccessTokenValiditySeconds(String clientId) {
|
||||
ClientDto clientDetails = (ClientDto)redisson.getBucket(clientRedisKey(clientId)).get();
|
||||
if (clientDetails != null) {
|
||||
return clientDetails.getAccessTokenValiditySeconds();
|
||||
}
|
||||
|
||||
//返回默认值
|
||||
return SecurityConstants.ACCESS_TOKEN_VALIDITY_SECONDS;
|
||||
}
|
||||
|
||||
private String clientRedisKey(String clientId) {
|
||||
return SecurityConstants.CACHE_CLIENT_KEY + ":" + clientId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新 access_token 的过期时间
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private void updateAccessTokenExpiresAt(OAuth2Authorization authorization, long validitySeconds) {
|
||||
try {
|
||||
Class<?> authClazz = authorization.getClass();
|
||||
Field tokensField = authClazz.getDeclaredField("tokens");
|
||||
tokensField.setAccessible(true);
|
||||
|
||||
Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>> tokens = (Map<Class<? extends OAuth2Token>, OAuth2Authorization.Token<?>>) tokensField.get(authorization);
|
||||
OAuth2Authorization.Token<OAuth2AccessToken> newToken = this.genateNewAccessToken(authorization.getAccessToken(), validitySeconds);
|
||||
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.updateListExpiresAt(this.getClientIdListKey(authorization), Duration.ofSeconds(validitySeconds));
|
||||
this.updateListExpiresAt(this.getUnameListKey(authorization), Duration.ofSeconds(validitySeconds));
|
||||
} catch (Exception e) {
|
||||
log.error("updateAccessTokenExpiresAt-error", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void removeList(OAuth2Authorization authorization) {
|
||||
this.redisListDelete(this.getClientIdListKey(authorization), authorization.getId());
|
||||
this.redisListDelete(this.getUnameListKey(authorization), authorization.getId());
|
||||
}
|
||||
|
||||
private void updateListExpiresAt(String key, Duration duration) {
|
||||
redisson.getList(key).expire(duration);
|
||||
}
|
||||
|
||||
private OAuth2Authorization.Token<OAuth2AccessToken> genateNewAccessToken(OAuth2Authorization.Token<OAuth2AccessToken> oldToken, long validitySeconds) {
|
||||
Instant issuedAt = Instant.now();
|
||||
Instant expiresAt = issuedAt.plus(Duration.ofSeconds(validitySeconds));
|
||||
|
||||
OAuth2AccessToken oldAccessToken = oldToken.getToken();
|
||||
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
|
||||
oldAccessToken.getTokenValue(), issuedAt,
|
||||
expiresAt, oldAccessToken.getScopes());
|
||||
return new CustomAccessToken(accessToken, oldToken.getMetadata());
|
||||
}
|
||||
|
||||
private Duration getExpireSeconds(OAuth2Token oAuth2Token) {
|
||||
return Duration.ofSeconds(
|
||||
ChronoUnit.SECONDS.between(oAuth2Token.getIssuedAt(), oAuth2Token.getExpiresAt()));
|
||||
}
|
||||
|
||||
private RBucket<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;
|
||||
}
|
||||
|
||||
private String getClientIdListKey(OAuth2Authorization authorization) {
|
||||
return this.getClientIdListKey(authorization.getRegisteredClientId());
|
||||
}
|
||||
private String getClientIdListKey(String clientId) {
|
||||
return buildKey(SecurityConstants.REDIS_CLIENT_ID_TO_ACCESS, clientId);
|
||||
}
|
||||
private String getUnameListKey(OAuth2Authorization authorization) {
|
||||
return this.getUnameListKey(authorization.getRegisteredClientId(), authorization.getPrincipalName());
|
||||
}
|
||||
private String getUnameListKey(String clientId, String username) {
|
||||
return buildKey(SecurityConstants.REDIS_UNAME_TO_ACCESS, clientId + "::" + username);
|
||||
}
|
||||
|
||||
private OAuth2Authorization redisBucketGet(String type, String id) {
|
||||
return (OAuth2Authorization)redisson.getBucket(buildKey(type, id), AUTH_CODEC).get();
|
||||
}
|
||||
|
||||
private RList<String> redisListAdd(String key, String value, Duration duration) {
|
||||
RList<String> rList = redisson.getList(key);
|
||||
rList.add(value);
|
||||
rList.expire(duration);
|
||||
return rList;
|
||||
}
|
||||
|
||||
private RList<String> redisListDelete(String key, String value) {
|
||||
RList<String> rList = redisson.getList(key);
|
||||
rList.remove(value);
|
||||
return rList;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ import java.util.Map;
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
public class CustomAccessToken extends OAuth2Authorization.Token<OAuth2AccessToken> {
|
||||
protected CustomAccessToken(OAuth2AccessToken token, Map metadata) {
|
||||
public CustomAccessToken(OAuth2AccessToken token, Map metadata) {
|
||||
super(token, metadata);
|
||||
}
|
||||
}
|
||||
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.central.oauth2.common.token;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 表单登录的认证信息对象
|
||||
*
|
||||
* @author zlt
|
||||
* @version 1.0
|
||||
* @date 2021/7/24
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Getter
|
||||
public class CustomWebAuthenticationDetails implements Serializable {
|
||||
private static final long serialVersionUID = - 1;
|
||||
|
||||
private final String accountType;
|
||||
private final String remoteAddress;
|
||||
private final String sessionId;
|
||||
|
||||
public CustomWebAuthenticationDetails(String remoteAddress, String sessionId, String accountType) {
|
||||
this.remoteAddress = remoteAddress;
|
||||
this.sessionId = sessionId;
|
||||
this.accountType = accountType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(super.toString()).append("; accountType: ").append(this.getAccountType());
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.central.oauth2.common.token;
|
||||
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.SpringSecurityCoreVersion;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
|
||||
|
||||
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
|
||||
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
private final Object principal;
|
||||
private Object credentials;
|
||||
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
/**
|
||||
* This constructor can be safely used by any code that wishes to create a
|
||||
* <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
|
||||
* will return <code>false</code>.
|
||||
*
|
||||
*/
|
||||
public MobileAuthenticationToken(String mobile, String password) {
|
||||
super(null);
|
||||
this.principal = mobile;
|
||||
this.credentials = password;
|
||||
setAuthenticated(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* This constructor should only be used by <code>AuthenticationManager</code> or
|
||||
* <code>AuthenticationProvider</code> implementations that are satisfied with
|
||||
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
|
||||
* authentication token.
|
||||
*
|
||||
* @param principal
|
||||
* @param authorities
|
||||
*/
|
||||
public MobileAuthenticationToken(Object principal, Object credentials,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(authorities);
|
||||
this.principal = principal;
|
||||
this.credentials = credentials;
|
||||
super.setAuthenticated(true);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return this.credentials;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return this.principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) {
|
||||
if (isAuthenticated) {
|
||||
throw new IllegalArgumentException(
|
||||
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
|
||||
}
|
||||
super.setAuthenticated(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eraseCredentials() {
|
||||
super.eraseCredentials();
|
||||
}
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
package com.central.oauth2.common.token;
|
||||
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.SpringSecurityCoreVersion;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author zlt
|
||||
*/
|
||||
public class OpenIdAuthenticationToken extends AbstractAuthenticationToken {
|
||||
|
||||
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
|
||||
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
private final Object principal;
|
||||
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
/**
|
||||
* This constructor can be safely used by any code that wishes to create a
|
||||
* <code>UsernamePasswordAuthenticationToken</code>, as the {@link #isAuthenticated()}
|
||||
* will return <code>false</code>.
|
||||
*
|
||||
*/
|
||||
public OpenIdAuthenticationToken(String openId) {
|
||||
super(null);
|
||||
this.principal = openId;
|
||||
setAuthenticated(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* This constructor should only be used by <code>AuthenticationManager</code> or
|
||||
* <code>AuthenticationProvider</code> implementations that are satisfied with
|
||||
* producing a trusted (i.e. {@link #isAuthenticated()} = <code>true</code>)
|
||||
* authentication token.
|
||||
*
|
||||
* @param principal
|
||||
* @param authorities
|
||||
*/
|
||||
public OpenIdAuthenticationToken(Object principal,
|
||||
Collection<? extends GrantedAuthority> authorities) {
|
||||
super(authorities);
|
||||
this.principal = principal;
|
||||
super.setAuthenticated(true);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return this.principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) {
|
||||
if (isAuthenticated) {
|
||||
throw new IllegalArgumentException(
|
||||
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
|
||||
}
|
||||
super.setAuthenticated(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eraseCredentials() {
|
||||
super.eraseCredentials();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.central.oauth2.common.token;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author: zlt
|
||||
* @date: 2023/11/18
|
||||
* <p>
|
||||
* Blog: https://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
@Getter
|
||||
public class PasswordAuthenticationToken extends BaseAuthenticationToken {
|
||||
public static final AuthorizationGrantType GRANT_TYPE = new AuthorizationGrantType("password");
|
||||
private final Object principal;
|
||||
private final String credentials;
|
||||
|
||||
public PasswordAuthenticationToken(String username, String password) {
|
||||
super(GRANT_TYPE);
|
||||
this.principal = username;
|
||||
this.credentials = password;
|
||||
super.setAuthenticated(true);
|
||||
}
|
||||
|
||||
public PasswordAuthenticationToken(UserDetails user, String password, Collection<? extends GrantedAuthority> authorities) {
|
||||
super(authorities);
|
||||
this.principal = user;
|
||||
this.credentials = password;
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.central.oauth2.common.token;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* 增加租户id,解决不同租户单点登录时角色没变化
|
||||
*
|
||||
* @author zlt
|
||||
* @date 2020/6/10
|
||||
* <p>
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
public class TenantUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken {
|
||||
private static final long serialVersionUID = -5638287853803374687L;
|
||||
|
||||
/**
|
||||
* 租户id
|
||||
*/
|
||||
@Getter
|
||||
private final String clientId;
|
||||
|
||||
public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials, String clientId) {
|
||||
super(principal, credentials);
|
||||
this.clientId = clientId;
|
||||
}
|
||||
|
||||
public TenantUsernamePasswordAuthenticationToken(Object principal, Object credentials,
|
||||
Collection<? extends GrantedAuthority> authorities, String clientId) {
|
||||
super(principal, credentials, authorities);
|
||||
this.clientId = clientId;
|
||||
}
|
||||
}
|
||||
+24
-56
@@ -3,14 +3,12 @@ package com.central.oauth2.common.util;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.constant.SecurityConstants;
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.model.SysUser;
|
||||
import com.central.common.model.LoginAppUser;
|
||||
import com.central.common.utils.LoginUserUtils;
|
||||
import com.central.oauth2.common.exception.CustomOAuth2AuthenticationException;
|
||||
import com.central.oauth2.common.token.BaseAuthenticationToken;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
||||
|
||||
@@ -18,8 +16,10 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
||||
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
|
||||
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.Principal;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
@@ -79,36 +79,33 @@ public class AuthUtils {
|
||||
/**
|
||||
* 校验accessToken
|
||||
*/
|
||||
public static SysUser checkAccessToken(HttpServletRequest request) {
|
||||
public static LoginAppUser checkAccessToken(HttpServletRequest request) {
|
||||
String accessToken = extractToken(request);
|
||||
return checkAccessToken(accessToken);
|
||||
}
|
||||
|
||||
public static SysUser checkAccessToken(String accessTokenValue) {
|
||||
OAuth2AuthorizationService tokenService = SpringUtil.getBean(OAuth2AuthorizationService.class);
|
||||
OAuth2Authorization oAuth2Authorization = tokenService.findByToken(accessTokenValue, OAuth2TokenType.ACCESS_TOKEN);
|
||||
if (oAuth2Authorization == null || oAuth2Authorization.getAccessToken() == null) {
|
||||
throw new CustomOAuth2AuthenticationException("Invalid access token: " + accessTokenValue);
|
||||
} else if (oAuth2Authorization.getAccessToken().isExpired()) {
|
||||
tokenService.remove(oAuth2Authorization);
|
||||
throw new CustomOAuth2AuthenticationException("Access token expired: " + accessTokenValue);
|
||||
public static LoginAppUser checkAccessToken(String accessTokenValue) {
|
||||
OAuth2Authorization authorization = checkAccessTokenToAuth(accessTokenValue);
|
||||
Authentication authentication = (Authentication)authorization.getAttributes().get(Principal.class.getName());
|
||||
if (authentication == null) {
|
||||
throw new OAuth2IntrospectionException("Invalid access token: " + accessTokenValue);
|
||||
}
|
||||
/*OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
|
||||
if (result == null) {
|
||||
throw new OAuth2AuthenticationException("Invalid access token: " + accessTokenValue);
|
||||
}*/
|
||||
// TODO 如何生成 Authentication 对象
|
||||
return setContext(null);
|
||||
return LoginUserUtils.setContext(authentication);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户信息赋值 context 对象
|
||||
*/
|
||||
public static SysUser setContext(Authentication authentication) {
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
SysUser user = getUser(authentication);
|
||||
LoginUserContextHolder.setUser(user);
|
||||
return user;
|
||||
public static OAuth2Authorization checkAccessTokenToAuth(String accessTokenValue) {
|
||||
if (accessTokenValue == null) {
|
||||
throw new OAuth2IntrospectionException("Invalid access token: " + null);
|
||||
}
|
||||
OAuth2AuthorizationService authorizationService = SpringUtil.getBean(OAuth2AuthorizationService.class);
|
||||
OAuth2Authorization authorization = authorizationService.findByToken(accessTokenValue, OAuth2TokenType.ACCESS_TOKEN);
|
||||
if (authorization == null || authorization.getAccessToken() == null) {
|
||||
throw new OAuth2IntrospectionException("Invalid access token: " + accessTokenValue);
|
||||
} else if (authorization.getAccessToken().isExpired()) {
|
||||
authorizationService.remove(authorization);
|
||||
throw new OAuth2IntrospectionException("Access token expired: " + accessTokenValue);
|
||||
}
|
||||
return authorization;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,35 +144,6 @@ public class AuthUtils {
|
||||
return clientArr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登陆的用户名
|
||||
*/
|
||||
public static String getUsername(Authentication authentication) {
|
||||
Object principal = authentication.getPrincipal();
|
||||
String username = null;
|
||||
if (principal instanceof SysUser) {
|
||||
username = ((SysUser) principal).getUsername();
|
||||
} else if (principal instanceof String) {
|
||||
username = (String) principal;
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登陆的用户对象
|
||||
*/
|
||||
public static SysUser getUser(Authentication authentication) {
|
||||
SysUser user = null;
|
||||
if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
|
||||
Object principal = authentication.getPrincipal();
|
||||
//客户端模式只返回一个clientId
|
||||
if (principal instanceof SysUser) {
|
||||
user = (SysUser)principal;
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取登陆的帐户类型
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user