Java 伪请求拦截器动态值
我是一些API的客户端,我需要在每个请求中发送一个令牌,为了获得这个令牌,我需要访问Java 伪请求拦截器动态值,java,feign,Java,Feign,我是一些API的客户端,我需要在每个请求中发送一个令牌,为了获得这个令牌,我需要访问/auth/token发送用户名和密码,并考虑使用请求拦截器来解决它。但是每个请求的用户名和密码是不同的,在我需要使用普通的外国客户机调用/auth/token的每个API调用之前,是否有某种方法在外国请求拦截器中使用动态值 我有一个服务可以访问此令牌API @Service @RequiredArgsConstructor public class AuthService { private final A
/auth/token
发送用户名和密码,并考虑使用请求拦截器来解决它。但是每个请求的用户名和密码是不同的,在我需要使用普通的外国客户机调用/auth/token
的每个API调用之前,是否有某种方法在外国请求拦截器中使用动态值
我有一个服务
可以访问此令牌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());
}
}
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);
}
用于访问令牌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());
}
}
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);
}
以及使用此服务的请求拦截器
@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());
}
}
我不知道如何在构建外部客户端时添加此拦截器,以设置每个请求的用户。使用Spring时,您需要将请求拦截器注册为@Bean
,以便自动应用它。如果您没有使用Spring或手动构建外部客户端,请使用Feign.builder.interceptor()
方法注册拦截器。是的,这是可能的。你能展示一下到目前为止你都做了些什么吗?我也有类似的情况。就我记忆所及,在“private final AuthUser user user”中如何获取用户?由于每个请求有不同的用户,我们最终没有使用请求拦截器