whatspoppin
whatspoppin

Reputation: 383

add Authorization token using Feign client

I have two service connected to a registry, one of them need to query some data from the other, the token need to be passed to the endpoint.

I Have tried the following but it didn't work, the endpoint act as if no token is provided.

    @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);

Upvotes: 2

Views: 2565

Answers (3)

Vladimir Stanciu
Vladimir Stanciu

Reputation: 1526

Should work like this @RequestHeader(value = "Authorization") String authorization, but make sure you pass the right value, must be something like Bearer token.

Upvotes: 2

Deepu George Jacob
Deepu George Jacob

Reputation: 474

Create Header like this and pass to your feign client

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

Example 1

Or very simple add intercepter

@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

Upvotes: 0

Tushar Jajodia
Tushar Jajodia

Reputation: 451

Your this code is absolutely correct.

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

Just when you are calling this particular method add "Bearer " in front of the value of the token

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

Upvotes: 1

Related Questions