我是一些API的客户端,我需要在每个请求中发送一个令牌,为了获得这个令牌,我需要访问发送用户名和密码的/auth/token
,并考虑使用请求拦截器来解决它。但是每个请求的用户名和密码是不同的,有一些方法可以在假装请求拦截器中使用动态值,或者在每次调用API之前,我都需要使用普通的冒充客户端调用/auth/token
?
我有一个访问此令牌API的Service
。
@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());
}
}
访问令牌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);
}
以及使用此服务的RequestInterceptor
@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());
}
}
我不知道在构建假冒伪劣客户端以设置每个请求时如何添加这个拦截器
发布于 2019-05-20 06:42:55
使用Spring时,需要将RequestInterceptor
注册为@Bean
才能自动应用它。如果您不使用Spring,或者手动构建假冒伪劣客户端,请使用Feign.builder.interceptor()
方法注册拦截器。
发布于 2021-07-22 00:57:37
在假装的@Configuration
类中添加一个拦截bean:
@Bean
public RequestInterceptor myInterceptor() {
return template -> {
// For example, add a header to an intercepted query:
template.header(
MY_HEADER_NAME,
MY_HEADER_VALUE);
};
}
https://stackoverflow.com/questions/53085554
复制相似问题