Spring boot Oauth2 : Token relay from a client using Feign, Ribbon, Zull and Eureka to a ressource

百般思念 提交于 2020-01-06 04:46:05

问题


I have an oauth2 client that get a token from an authorization server successfully. (not always has been the case but now it is... :))

The client, the zuul gateway and the resource server are all registered in Eureka.

My client use a Proxy to access to a remote ressource service named microservice-files.

@RestController
@FeignClient(name = "zuul-server")
@RibbonClient(name = "microservice-files")

public interface ProxyMicroserviceFiles {

    @GetMapping(value = "microservice-files/root")
    FileBean getUserRoot();

}

So I'd like to relay the token to Zull and then to the resource server.

I can relay the token this way to contact Zuul and apparently the load balancing is managed too (I've just test I didn't know and it's great) also zuul can relay the token, but it's not very convenient I'd prefer the previous approach.

@EnableConfigurationProperties
@SpringBootApplication
@EnableFeignClients("com.clientui")
public class ClientUiApplication {

    @Bean
    public OAuth2RestOperations restOperations(
            OAuth2ProtectedResourceDetails resource, 
            OAuth2ClientContext context) {

        return new OAuth2RestTemplate(resource, context);
    }

    public static void main(String[] args) {

        SpringApplication.run(ClientUiApplication.class, args);
    }
}

here is the test controler

@Controller
public class ClientController {

    @Autowired
    private RestOperations restOperations;

    @RequestMapping("/root")
    public ResponseEntity userRootTest() {

       String rootUrl = "http://localhost:9004/microservice-files/root";

       return  restOperations.getForEntity(rootUrl,FileBean.class);

    }

}

回答1:


If I correctly understand your problem then you can use a RequestInterceptor to add a token in each request by the feign. In order to do it you can use the next configuration:

@Bean
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oauth2ClientContext,
                                                        OAuth2ProtectedResourceDetails resource) {
    return new OAuth2FeignRequestInterceptor(oauth2ClientContext, resource);
}

@Bean
protected OAuth2ProtectedResourceDetails resource() {
    AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
    resource.setAccessTokenUri("http://127.0.0.1:9000/auth/login");
    resource.setUserAuthorizationUri("http://127.0.0.1:9000/auth/authorize");
    resource.setClientId("my-client");
    resource.setClientSecret("my-secret");
    return resource;
}


来源:https://stackoverflow.com/questions/53414705/spring-boot-oauth2-token-relay-from-a-client-using-feign-ribbon-zull-and-eur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!