java 使用Feign客户端添加授权令牌

myzjeezk  于 2023-02-20  发布在  Java
关注(0)|答案(3)|浏览(233)

我有两个服务连接到一个注册中心,其中一个需要从另一个查询一些数据,令牌需要传递到端点。
我尝试了以下方法,但没有成功,端点的行为就像没有提供令牌一样。

@GetMapping("/api/users/find")
    @Headers("Authorization: Bearer {token}")
    Optional<UserDTO> findUserByEmail(
        @Param("token") String token, @RequestParam("email") String email);
@GetMapping("/api/users/find")
    Optional<UserDTO> findUserByEmail(
        @RequestHeaders("Authorization") String token, @RequestParam("email") String email);
@GetMapping("/api/users/find")
    Optional<UserDTO> findUserByEmail(
        @HeaderMap Map<String, Object> headers , @RequestParam("email") String email);
syqv5f0l

syqv5f0l1#

应该像@RequestHeader(value = "Authorization") String authorization这样工作,但要确保传递正确的值,必须像Bearer token这样。

mm9b1k5b

mm9b1k5b2#

你的这个代码是绝对正确的。

@GetMapping("/api/users/find")
    Optional<UserDTO> findUserByEmail(
    @RequestHeaders("Authorization") String token, @RequestParam("email") String email);

就在调用这个特定方法时,在令牌值前面添加“Bearer

token = "Bearer " + token;
findUserByEmail(token,email);
pieyvz9o

pieyvz9o3#

像这样创建Header并传递给您的假客户端

private HttpHeaders getHeaders(final HttpServletRequest httpServletRequest) {
        final HttpHeaders headers = new HttpHeaders();
        headers.add("authorization", httpServletRequest.getHeader("authorization"));
        return headers;

Example 1
或者非常简单的添加拦截器

@Component
public class AuthFeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            final HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
            template.header(HttpHeaders.AUTHORIZATION, httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION));
        }
    }
}

Example 2

相关问题