Search code examples
javaspring-bootspring-securityoauth-2.0

How to use Spring Boot feign client for Oauth2 authentication?


I have an oauth server at localhost and want to call it from another service uisng feign-client for authenticating me and giving me some token.

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

Here is how my pass the basic auth details

How to do the same functionality using FeignClient in Spring Boot?


Solution

  • put @EnableFeignClients in the spring boot main application java class . create after an Feign client interface to call the web service :

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

    and ClientFallbackFactory as :

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

    Your RequestBody might be a java class :

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

    }

    and The ResponseVo class :

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

    }

    and you can add thise config :

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