有一条微服务链通过 eureka 和 gateway-api 进行交互。
在其中,传递了一个令牌以进行身份验证。但是在微服务 #1 中,我使用 Feign 来调用
微服务 #2。为了将令牌传递给#2,我创建了一个 RequestInterceptor bean。
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
System.out.println("In the request interceptor");
System.out.println(SecurityContextHolder.getContext());
System.out.println(SecurityContextHolder.getContext().getAuthentication());
JwtAuthenticationToken token = (JwtAuthenticationToken) SecurityContextHolder
.getContext().getAuthentication();
requestTemplate.header("Authorization", "Bearer" + token.getToken().getTokenValue());
}
};
}
}
但是由于某种原因,当在拦截器 bean 中通过邮递员发送请求时,SecurityContextHolder.getContext().getAuthentication() 值返回 null。
签入控制器时,很明显令牌到达
@RestController
@RequestMapping("/api/order")
@Slf4j
@RequiredArgsConstructor
public class OrderController {
private final OrderRepository orderRepository;
private final InventoryClient inventoryClient;
@PostMapping
public String placeOrder(@RequestBody OrderDto orderDto, @RequestHeader("Authorization") String authHeader) {
System.out.println("In the order controller");
System.out.println("Authorization:" + authHeader);
boolean isAllProductsInStock = orderDto.getOrderLineItems().stream()
.allMatch(orderLineItem -> inventoryClient.checkStock(orderLineItem.getScuCode()));
if (isAllProductsInStock) {
Order order = new Order();
order.setOrderLineItems(orderDto.getOrderLineItems());
order.setOrderNumber(UUID.randomUUID().toString());
orderRepository.save(order);
return "Order place successfully";
}
return "Please try again";
}
}
令牌输出到控制台:授权:承载 eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ5cXNCUnktOVFBZ0pJZmFxa2VybVNVMEQ0UGVCalFpRTNtNF9RRnVjMlowIn0。eyJleHAiOjE2NjA4OTgwOTUsImlhdCI6MTY2MDg5Nzc5NSwiYXV0aF90aW1lIjoxNjYw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