Попытка использовать токен Oauth2 с фальшивым клиентом и гистриксом

Я пытаюсь вызвать «ServiceB» из «ServiceA», обе службы являются сервером ресурсов, я пытаюсь выполнить этот межсервисный вызов через «Feign Client and OAuth2 toke», который отлично работает с приведенной ниже реализацией bean-компонентов в классе конфигурации. :

@Bean    
public RequestInterceptor requestTokenBearerInterceptor() {

    return new RequestInterceptor() {

        @Override
        public void apply(RequestTemplate requestTemplate) {

            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)

            SecurityContextHolder.getContext().getAuthentication()
                    .getDetails();

            requestTemplate.header("Authorization",
                    "bearer " + details.getTokenValue());

        }

    };

}

Когда я пытаюсь использовать клиент Feign с резервным вариантом, то есть Hystrix без токена OAuth (т.е. когда ни одна из служб не является сервером ресурсов), он также работает нормально.

Но при попытке использовать три из них (например, Feignclient, Hystrix и OAuth2) вместе, это не работает. Каждый раз он будет использовать резервный метод, хотя все службы работают.

Ниже мой код:

App.java

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContextHolder;
import        org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import feign.RequestInterceptor;
import feign.RequestTemplate;


@SpringBootApplication
@RestController
@EnableFeignClients
@EnableEurekaClient
@EnableCircuitBreaker
public class App 
{

/*@Autowired
@Qualifier("abc")
private GitHubClient gitHub;*/
@Autowired
private CallService callService;
public static void main( String[] args )
{
    SpringApplication.run(App.class, args);
}
    @RequestMapping(value="/feign",method=RequestMethod.POST,consumes="application/json")
public String contributors1(@RequestBody JSONObject payLoad) {
        String callservice2 = callService.callservice(payLoad);
        return callservice2;
}

@Bean
public RequestInterceptor requestTokenBearerInterceptor() {

    return new RequestInterceptor() {

        @Override
        public void apply(RequestTemplate requestTemplate) {

            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)

            SecurityContextHolder.getContext().getAuthentication()
                    .getDetails();

            requestTemplate.header("Authorization",
                    "bearer " + details.getTokenValue());

        }

    };

}



}

Callervice.java

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class CallService {


@Autowired
@Qualifier("abc")
private GitHubClient gitHub;

public String callservice(JSONObject payLoad){
    String forObject =gitHub.contributors(payLoad);
    return forObject;
}

}

HystrixWrappedClient.java

import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Component("abc")
public class HystrixWrappedClient implements GitHubClient{

@Autowired
@Qualifier("gitHubClient")
private GitHubClient gitHub;

@Override
@HystrixCommand(fallbackMethod="failure")
public String contributors(JSONObject payLoad) {
    return gitHub.contributors(payLoad);
}

public String failure(JSONObject payLoad){
    System.out.println(payLoad);
    return "Failure";
}
}

GitHubClient.java

import org.json.simple.JSONObject;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient("MockRestService")
interface GitHubClient {


@RequestMapping(method = RequestMethod.POST, value =     "/test",consumes="application/json")
String contributors(@RequestBody JSONObject payLoad);

}

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>


<dependencies>
    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-client</artifactId>
        <version>1.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
        <version>1.0.1.RELEASE</version>
    </dependency>
    <!-- For swagger documenation -->
    <dependency>
        <groupId>com.mangofactory</groupId>
        <artifactId>swagger-springmvc</artifactId>
        <version>1.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
    </dependency>

    <!-- NEW -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>


</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-parent</artifactId>
            <version>1.0.1.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Пожалуйста, предложите. Всякий раз, когда вы пытаетесь использовать Feignclient, OAuth2 и Hystrix вместе, он всегда переходит к методу Fallback.


person Debjyoti    schedule 08.02.2016    source источник


Ответы (2)


Вы каким-то образом поделились контекстом Spring Security с Hystrix?

Начиная с Spring Cloud Netflix 1.2.0, вы можете включить совместное использование контекста безопасности с Hystrix, используя параметр конфигурации.

hystrix.shareSecurityContext: true

person Ondrej Bozek    schedule 24.03.2017

Вы можете изучить этот http://kodgemisi.com/2017/02/use-securitycontext-feign-requestinterceptor/ Выполнение Hystrix в другом / другом потоке, передача контекста безопасности с помощью HystrixRequestVariableDefault

person SUGENAN    schedule 23.03.2017