重構-改善既有代碼的設計,重構的目的是是軟件更容易被理解和修改。git
書接上回Spring Security OAuth 微服務內部Token傳遞的源碼解析,本篇主要無token 調用過程當中,代碼的不斷完善及其重構過程。spring
需求很簡單以下圖,若是資源服務器的提供的接口,客戶端不須要身份驗證即不須要攜帶合法令牌也能訪問,而且能夠實現遠程調用的安全性校驗。 api
ignore-urls:
- /actuator/**
- /v2/api-docs
複製代碼
/**
* @author lengleng
* <p>
* 服務間接口不鑑權處理邏輯
*/
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class PigxSecurityInnerAspect {
private final HttpServletRequest request;
@SneakyThrows
@Around("@annotation(inner)")
public Object around(ProceedingJoinPoint point, Inner inner) {
String header = request.getHeader(SecurityConstants.FROM);
if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
log.warn("訪問接口 {} 沒有權限", point.getSignature().getName());
throw new AccessDeniedException("Access is denied");
}
return point.proceed();
}
}
複製代碼
public class PigxRequestGlobalFilter implements GlobalFilter, Ordered {
private static final String HEADER_NAME = "X-Forwarded-Prefix";
/**
* Process the Web request and (optionally) delegate to the next
* {@code WebFilter} through the given {@link GatewayFilterChain}.
*
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next filter
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. 清洗請求頭中from 參數
ServerHttpRequest request = exchange.getRequest().mutate()
.headers(httpHeaders -> {httpHeaders.remove(SecurityConstants.FROM);})
.build();
return chain.filter(exchange.mutate()
.request(newRequest.mutate()
.header(HEADER_NAME, basePath)
.build()).build());
}
@Override
public int getOrder() {
return -1000;
}
}
複製代碼
ignore-urls:
- /info/*
複製代碼
@Inner
@GetMapping("/info/{username}")
public R info(@PathVariable String username) {
}
複製代碼
public class PermitAllUrlProperties implements InitializingBean {
private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
@Autowired
private WebApplicationContext applicationContext;
@Getter
@Setter
private List<String> ignoreUrls = new ArrayList<>();
@Override
public void afterPropertiesSet() {
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
map.keySet().forEach(info -> {
HandlerMethod handlerMethod = map.get(info);
// 獲取方法上邊的註解 替代path variable 爲 *
Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);
Optional.ofNullable(method)
.ifPresent(inner -> info.getPatternsCondition().getPatterns()
.forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK))));
});
}
}
複製代碼
@Inner(value=false)
複製代碼
@Inner
複製代碼
歡迎關注咱們得到更多的好玩JavaEE 實踐安全