【问题标题】:How to request Feign with Authentication JWT Bearer Java Spring?如何使用身份验证 JWT Bearer Java Spring 请求 Feign?
【发布时间】:2021-07-03 09:35:21
【问题描述】:
我在 java spring service core 和 service shop 中使用了两个服务,我想用 service core 中的方法从 service core 插入数据,但是在 service core 中我需要不记名令牌,我如何从 service shop 发送身份验证不记名令牌服务核心?
【问题讨论】:
标签:
java
spring
spring-boot
spring-security
spring-cloud-feign
【解决方案1】:
当然,您需要一种使用client-credentials 授权类型从众所周知的 OAuth 端点获取服务令牌的方法
如果您想在每个集成的基础上执行此操作,可能是因为您使用不同的方法与不同的服务集成,您可以执行以下操作:
@RequestMapping(method = [RequestMethod.GET], value = ["/id/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType.APPLICATION_JSON_VALUE])
operator fun get(
@RequestHeader("Authorization") bearerToken: String = "Bearer mybiglongencodedtoken....",
@PathVariable("id") code: String,
【解决方案2】:
实现RequestInterceptor 将身份验证设置为请求标头。
public void apply(RequestTemplate template) {
if (RequestContextHolder.getRequestAttributes() != null && RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
String authorization = request.getHeader("Authorization");
if (StringUtils.isNotBlank(authorization)) {
template.header("Authorization", new String[]{authorization});
}
}
}