Skip to content

Commit

Permalink
重构和增强平台安全模块的多个组件,包括oauth2配置、安全细节处理、权限请求和响应处理。优化了代码逻辑,提高了代码复用性和可维护性。具体包括:
Browse files Browse the repository at this point in the history
- 简化`AbstractService`中`afterPropertiesSet`方法的日志输出。
- 删除`BeanUtils`中的`cacheKey`和`cachePut`方法,同时调整`cacheKey`的实现。
- 在`JsonException`中修改错误代码。
- 移除`RestServerException`中不必要的包名定义。
- 在`SecurityConfiguration`中使用`BeanUtils`替换`ContextUtils`进行对象转字节操作。
- 修改`TenantRequest`和`UserAuthorityRequest`中的查询参数。
- 在`Oauth2SuccessHandler`中调整对象序列化方法。
- 其他各种代码优化和清理。

这些更改提升了代码质量,增强了组件之间的解耦,并为平台安全模块提供了更好的扩展性和灵活性。
  • Loading branch information
vnobo committed Aug 15, 2024
1 parent 024dde2 commit 2ff49a3
Show file tree
Hide file tree
Showing 13 changed files with 54 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ public void setObjectMapper(ObjectMapper objectMapper) {

@Override
public void afterPropertiesSet() {
log.debug("Initializing provider names: %s".formatted(this.getClass().getName()));
log.debug("Initializing provider names: {}",this.getClass().getName());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.unit.DataSize;
Expand All @@ -18,7 +17,6 @@
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.Objects;

/**
* @author <a href="https://github.com/vnobo">Alex bob</a>
Expand All @@ -40,21 +38,6 @@ public final class BeanUtils implements InitializingBean {
}
}

public static String cacheKey(Object... objects) {
int hashCode = Objects.hash(objects);
return String.valueOf(hashCode);
}

public static void cachePut(Cache cache, String cacheKey, Object obj) {
DataSize objectSize = getBeanSize(obj);
if (objectSize.toBytes() > MAX_IN_MEMORY_SIZE.toBytes()) {
log.warn("Object size is too large, Max memory size is {}, Object size is {}.",
MAX_IN_MEMORY_SIZE, objectSize);
return;
}
cache.put(cacheKey, obj);
}

public static DataSize getBeanSize(Object obj) {
if (ObjectUtils.isEmpty(obj)) {
log.warn("Object is empty,This object not null.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@
*/
public record ErrorResponse(String requestId, String path, Integer code,
String message, Object errors, LocalDateTime time) implements Serializable {
/**
* 创建一个错误响应对象
*
* @param requestId 请求的唯一标识符
* @param path 请求的路径
* @param code 错误代码
* @param message 错误消息
* @param errors 附加错误信息
* @return 返回新创建的错误响应对象
*/
public static ErrorResponse of(String requestId, String path, Integer code, String message, Object errors) {
return new ErrorResponse(requestId, path, code, message, errors, LocalDateTime.now());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ protected void initializingCache(String cacheName) {
this.cache = Optional.ofNullable(this.cacheManager).map(manager -> manager.getCache(cacheName))
.orElse(new ConcurrentMapCache(cacheName));
this.cache.clear();
log.debug("Initializing provider [%s] cache names: %s".formatted(
this.cache.getNativeCache().getClass().getSimpleName(), this.cache.getName()));
log.debug("Initializing provider [{}] cache names: {}",
this.cache.getNativeCache().getClass().getSimpleName(), this.cache.getName());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
public class JsonException extends RestServerException {

public JsonException(IOException jsonProcessingException) {
this(5010, "Json processing exception", jsonProcessingException);
this(500, "Json processing exception", jsonProcessingException);
}

public JsonException(int status, String message, Object msg) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Define the package name
package com.plate.boot.commons.exception;

import lombok.Data;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
package com.plate.boot.commons.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonPointer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.google.common.collect.Maps;
import com.plate.boot.commons.exception.JsonException;
import com.plate.boot.commons.exception.RestServerException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.unit.DataSize;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/**
* @author <a href="https://github.com/vnobo">Alex bob</a>
Expand All @@ -40,6 +46,33 @@ public final class BeanUtils implements InitializingBean {
}
}

public static <T> T jsonPathToBean(JsonNode json, String path, Class<T> clazz) {
try {
String[] paths = StringUtils.commaDelimitedListToStringArray(path);
StringJoiner pathJoiner = new StringJoiner("/");
for (String p : paths) {
pathJoiner.add(p);
}
JsonPointer jsonPointer = JsonPointer.valueOf(pathJoiner.toString());
JsonNode valueNode = json.at(jsonPointer);
if (valueNode.isMissingNode()) {
throw JsonException.withMsg("Json pointer path is not exist!",
"JsonPointer path is not exist!");
}
return ContextUtils.OBJECT_MAPPER.convertValue(valueNode, clazz);
} catch (IllegalArgumentException e) {
throw JsonException.withMsg("转换JsonPointer字符转异常!", e.getMessage());
}
}

public static <T> byte[] objectToBytes(T object) {
try {
return ContextUtils.OBJECT_MAPPER.writeValueAsBytes(object);
} catch (JsonProcessingException e) {
throw JsonException.withError(e);
}
}

public static String cacheKey(Object... objects) {
int hashCode = Objects.hash(objects);
return String.valueOf(hashCode);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package com.plate.boot.commons.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.f4b6a3.ulid.Ulid;
import com.github.f4b6a3.ulid.UlidCreator;
import com.plate.boot.commons.exception.JsonException;
import com.plate.boot.commons.exception.RestServerException;
import com.plate.boot.security.SecurityDetails;
import com.plate.boot.security.core.UserAuditor;
Expand Down Expand Up @@ -57,14 +55,6 @@ public final class ContextUtils implements InitializingBean {
ContextUtils.USERS_SERVICE = usersService;
}

public static byte[] objectToBytes(Object object) {
try {
return ContextUtils.OBJECT_MAPPER.writeValueAsBytes(object);
} catch (JsonProcessingException e) {
throw JsonException.withError(e);
}
}

public static String getClientIpAddress(ServerHttpRequest httpRequest) {
HttpHeaders headers = httpRequest.getHeaders();
for (String header : IP_HEADER_CANDIDATES) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.plate.boot.config;

import com.plate.boot.commons.ErrorResponse;
import com.plate.boot.commons.utils.ContextUtils;
import com.plate.boot.commons.utils.BeanUtils;
import com.plate.boot.security.oauth2.Oauth2SuccessHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
Expand Down Expand Up @@ -181,7 +181,7 @@ private Mono<Void> handleXmlHttpRequestFailure(ServerWebExchange exchange, Authe
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

ErrorResponse errorResponse = createErrorResponse(exchange, e);
var body = ContextUtils.objectToBytes(errorResponse);
var body = BeanUtils.objectToBytes(errorResponse);
var dataBufferFactory = response.bufferFactory();
var bodyBuffer = dataBufferFactory.wrap(body);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.util.ObjectUtils;
Expand Down Expand Up @@ -56,8 +55,7 @@ public final class SecurityDetails extends DefaultOAuth2User implements UserDeta

@JsonCreator
public SecurityDetails() {
super(Set.of(new SimpleGrantedAuthority("ROLE_NONE")),
Map.of("username", "any_none"), "username");
super(null, Map.of("username", "any_none"), "username");
}

public SecurityDetails(Collection<? extends GrantedAuthority> authorities,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ public Tenant toTenant() {
}

public ParamSql bindParamSql() {
return CriteriaUtils.buildParamSql(this, List.of("securityCode"), null);
return CriteriaUtils.buildParamSql(this, List.of(), null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public UserAuthority toAuthority() {
}

public Criteria toCriteria() {
return criteria(Set.of("authorities"));
return criteria(Set.of());
}

}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.plate.boot.security.oauth2;

import com.plate.boot.commons.exception.RestServerException;
import com.plate.boot.commons.utils.ContextUtils;
import com.plate.boot.commons.utils.BeanUtils;
import com.plate.boot.security.core.AuthenticationToken;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
Expand Down Expand Up @@ -63,7 +63,7 @@ private Mono<Void> handleXmlHttpRequest(ServerWebExchange exchange, OAuth2Authen
}

private Mono<Void> writeAuthenticationToken(ServerHttpResponse response, AuthenticationToken authenticationToken) {
var body = ContextUtils.objectToBytes(authenticationToken);
var body = BeanUtils.objectToBytes(authenticationToken);
var dataBufferFactory = response.bufferFactory();
var bodyBuffer = dataBufferFactory.wrap(body);
return response.writeAndFlushWith(Flux.just(bodyBuffer).windowUntilChanged());
Expand Down

0 comments on commit 2ff49a3

Please sign in to comment.