【问题标题】:How to use Spring Boot feign client for Oauth2 authentication?如何使用 Spring Boot feign 客户端进行 Oauth2 身份验证?
【发布时间】:2021-01-21 06:44:39
【问题描述】:

我在 localhost 有一个 oauth 服务器,我想从另一个服务 uisng feign-client 调用它来验证我的身份并给我一些令牌。

Here is how i pass my username,password and grant type i postman

Here is how my pass the basic auth details

如何在 Spring Boot 中使用 FeignClient 做同样的功能?

【问题讨论】:

    标签: java spring-boot spring-security oauth-2.0


    【解决方案1】:

    将@EnableFeignClients 放在spring boot 主应用java 类中。 在 Feign 客户端接口之后创建来调用 Web 服务:

        @FeignClient(value = "service-auth",
            configuration = ClientConfig.class,
            fallbackFactory = ClientFallbackFactory.class,
            url = "http://localhost:10000/oauth/")
        public interface GenericAbstractClient {
    
    
        @RequestMapping(value="/token",
                method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
                produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
        ResponseVo auth(@RequestBody RequestVo body);
    
    
    }
    

    和 ClientFallbackFactory 为:

        @Component
        class ClientFallbackFactory implements FallbackFactory<GenericAbstractClient> {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(ClientFallbackFactory.class);
    
    
       
    
         @Override
          public GenericAbstractClient create(Throwable cause) {
    
        return new GenericAbstractClient () {
    
    
          @Override
          public ResponseVo oauth(RequestVo body) {
            LOGGER.warn("Hystrix exception", cause.getMessage());
            return null;
          }
    
        
        };
    }
    }
    

    您的 RequestBody 可能是一个 java 类:

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class RequestVo {
    
    
    private String grant_type;
    private String username;
    private String password;
    

    }

    还有 ResponseVo 类:

        @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class ResponseVo {
    
    
    private String access_token;
    private String token_type;
    private String exprires_in;
    private String scope;
    

    }

    你可以添加这个配置:

    @Configuration
    public class ClientConfig {
    
    
        private int connectTimeOutMillis = 120000;
        private int readTimeOutMillis = 120000;
    
    
        @Bean
        public Request.Options options() {
            return new Request.Options(connectTimeOutMillis, readTimeOutMillis);
        }
    }
    

    【讨论】:

    • 我在哪里传递基本身份验证,即这里的客户端 ID 和密码详细信息?
    • 我邀请你看看这个link
    【解决方案2】:

    查看我关于如何让 client_credentials 在 https://stackoverflow.com/a/65741386/698471 上工作的回复,它会帮助你,这是相同的用例

    【讨论】:

      猜你喜欢
      • 2013-07-20
      • 1970-01-01
      • 2017-10-01
      • 2015-06-20
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      相关资源
      最近更新 更多