繁体   English   中英

如何使用 Spring Boot feign 客户端进行 Oauth2 身份验证?

[英]How to use Spring Boot feign client for Oauth2 authentication?

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

这是我如何传递我的用户名、密码和授权类型我邮递员

这是我如何传递基本身份验证详细信息

如何在 Spring Boot 中使用 FeignClient 执行相同的功能?

将 @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);
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM