I'm client of some APIs that I need to send a token in every request, and in order to get this token I need to access /auth/token
sending username and password, and thought about using a request interceptor to solve it. But username and password are different per request, there is some way to use dynamic values in feign request interceptor or before every API call I'll need to call /auth/token
using a normal feign client?
I have a Service
that access this token API
@Service
@RequiredArgsConstructor
public class AuthService {
private final AuthClient client;
private final AuthProperties properties;
@Cacheable("tokens")
public AuthToken getToken(AuthUser user) {
return client.authenticate(properties.getClientId(), properties.getSecret(), user.getUser(),
user.getPassword());
}
}
A feign client to access the token API
public interface AuthClient {
@RequestLine("GET /token?client_id={client_id}&client_secret={client_secret}&grant_type=password&username={username}&password={password}")
AuthToken authenticate(@Param("client_id") String client_id, @Param("client_secret") String client_secret,
@Param("username") String username, @Param("password") String password);
}
And a RequestInterceptor
that uses this service
@RequiredArgsConstructor
public class AuthRequestInterceptor implements RequestInterceptor {
private final AuthUser user;
@Autowired
private final AuthService authService;
@Override
public void apply(RequestTemplate template) {
AuthToken token = authService.getToken(user);
template.header("Authorization", "Bearer " + token.getAccess_token());
}
}
I'm not sure how to add this interceptor when building the feign client to set the user per request
When using Spring, you will need to register the RequestInterceptor
as a @Bean
to have it automatically applied. If you are not using Spring, or manually building Feign Clients, register the interceptor using the Feign.builder.interceptor()
method.