创建名为'scopedTarget.oauth2ClientContext'的bean时出错:当前线程的作用域'session'无效;

时间:2018-05-18 07:18:25

标签: java spring-boot microservices spring-cloud spring-oauth2

首先,我想说我搜索了我的问题并提出了建议,但这对我没有帮助。

我的来源如下:

@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "say-hello"/*, configuration = RibbonConfig.class*/)
@EnableAutoConfiguration
@EnableOAuth2Sso
public class HelloWorldStarter {

    public static void main(String[] args) {
        SpringApplication.run(HelloWorldStarter.class, args);
    }

    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }


    @RestController
    @EnableDiscoveryClient
    @EnableCircuitBreaker
    public static class HelloWorldController {
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private OAuth2RestTemplate oAuth2RestTemplate;
        @Autowired
        private DiscoveryClient discoveryClient;

        @GetMapping("/helloWorld")
        @HystrixCommand(fallbackMethod = "reliable")
        public String hello() {
            //String response = restTemplate.getForObject("http://localhost:8082/h/hello?name=World", String.class);
            try {
                return this.oAuth2RestTemplate.getForObject("http://hello-service/h/hello?name=World", String.class);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        public String reliable() {
            return "Could not get response from service";
        }
    }

    @org.springframework.context.annotation.Configuration
    public static class Configuration {
        @Bean
        @LoadBalanced
        RestTemplate restTemplate() {
            return new RestTemplate();
        }

        @Bean
        @ConfigurationProperties("security.oauth2")
        public ClientResources clientResources() {
            return new ClientResources();
        }

        @Autowired
        private OAuth2ClientContext oAuth2ClientContext;

        @Bean
        @LoadBalanced
        public OAuth2RestTemplate oAuth2RestTemplate() {
            return new OAuth2RestTemplate(clientResources().getClient(), oAuth2ClientContext);
        }

        class ClientResources {

            @NestedConfigurationProperty
            private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();

            @NestedConfigurationProperty
            private ResourceServerProperties resource = new ResourceServerProperties();

            public AuthorizationCodeResourceDetails getClient() {
                return client;
            }

            public ResourceServerProperties getResource() {
                return resource;
            }
        }
    }
}

application.yml:

spring:
  application:
    name: hello-world-service
server:
  port: 8081
  servlet:
    context-path: /hw
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka
  instance:
    preferIpAddress: true

security:
  oauth2:
    client:
      client-id: acme
      client-secret: acmesecret
      access-token-uri: http://localhost:8080/oauth/token
      user-authorization-uri: http://localhost:8080/oauth/authorize
    resource:
      user-info-uri: http://localhost:8080/me

logging:
  level:
    org.springframework.security: DEBUG
    org.springframework.web: DEBUG

当我调用/helloWorld Rest方法时,会发生以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.oauth2ClientContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:362)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:193)
    at com.sun.proxy.$Proxy116.getAccessToken(Unknown Source)
    at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:125)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:680)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:332)
    at org.ntkachev.microservices.hello_world.HelloWorldStarter$HelloWorldController.hello(HelloWorldStarter.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.netflix.hystrix.contrib.javanica.command.MethodExecutionAction.execute(MethodExecutionAction.java:116)
    at com.netflix.hystrix.contrib.javanica.command.MethodExecutionAction.executeWithArgs(MethodExecutionAction.java:93)
    at com.netflix.hystrix.contrib.javanica.command.MethodExecutionAction.execute(MethodExecutionAction.java:78)
    at com.netflix.hystrix.contrib.javanica.command.GenericCommand$1.execute(GenericCommand.java:48)
    at com.netflix.hystrix.contrib.javanica.command.AbstractHystrixCommand.process(AbstractHystrixCommand.java:145)
    at com.netflix.hystrix.contrib.javanica.command.GenericCommand.run(GenericCommand.java:45)
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302)
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298)
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46)
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.Observable.unsafeSubscribe(Observable.java:10151)
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51)
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
    at rx.Observable.unsafeSubscribe(Observable.java:10151)
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41)
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
    at rx.Observable.unsafeSubscribe(Observable.java:10151)
    at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94)
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56)
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47)
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction.call(HystrixContexSchedulerAction.java:69)
    at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
    at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
    at org.springframework.web.context.request.SessionScope.get(SessionScope.java:55)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:350)
    ... 47 more

在大多数答案中建议只添加

@Bean
public RequestContextListener requestContextListener() {
    return new RequestContextListener();
}

但是你可以看到这个建议已经应用了。

您能帮我执行其他服务的身份验证请求吗?

1 个答案:

答案 0 :(得分:0)

当我更正@HystrixCommand注释参数时问题消失了:

    @HystrixCommand(groupKey = "somethingProxy", commandKey = "retrieveSomething", ignoreExceptions = {
            IllegalArgumentException.class }, fallbackMethod = "reliable", commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy", value = "SEMAPHORE") })
    public String hello() {