Search code examples
oauth-2.0jhipsterhttp-status-code-403netflix-zuul

Error 403 when feign client makes POST/PUT request to micro-service


I've got a legacy app in java that can't use spring cloud. It uses a feign client to access a microservice throug the gateway.

Gateway and service are generated by jhipster 5.7.2 with OAuth2/OIDC option.

In my client, the a RequestInterceptor calls keycloak in order to get a token (direct access grant) and injects it int he header.

It's ok when I make a GET request, but I receive a 403 after POST or PUT request.

CORS is enabled on the gateway (but isn't used because the request isn't a cors request). I run it in dev mode. Zuul routes seem to be ok. I didn't change the config neither on the gateway nor on the service.

Does anybody have an idea ?

Below my feign client :

public interface SmartDocumentClient {

@RequestLine("GET /api/ebox/test")
//@Headers("Content-Type: application/json")
public ResponseEntity<HasEboxResponse> test();

@RequestLine("POST /api/ebox/test")
@Headers("Content-Type: application/json")
public ResponseEntity<HasEboxResponse> testPost(HasEboxRequest request);

@RequestLine("PUT /api/ebox/test")
@Headers("Content-Type: application/json")
public ResponseEntity<HasEboxResponse> testPut(HasEboxRequest request); }

My client config :

T client = Feign.builder()
            .contract(new feign.Contract.Default()) //annotation openfeign pour éviter bug d'upload avec SpringMvc
            .client(new OkHttpClient())
            .encoder(new FormEncoder(new GsonEncoder())) //pour gérer le formData
            .decoder(new ResponseEntityDecoder(new ResponseEntityDecoder(new CustomFileDecoder(new CustomGsonDecoder()))))
            .requestInterceptor(interceptor)
            .options(new Request.Options(timeout, timeout))
            .target(SmartDocumentClient, url);

The interceptor :

public class GedRequestInterceptor implements RequestInterceptor {

public static final String AUTHORIZATION = "Authorization";
public static final String BEARER = "Bearer";

private String authUrl;
private String user;
private String password;
private String clientId;
private String clientSecret;

private RestTemplate restTemplate;
private CustomOAuth2ClientContext oAuth2ClientContext;

public GedRequestInterceptor(String authUrl, String user, String password, String clientId, String clientSecret) {
    super();
    this.authUrl = authUrl;
    this.user = user;
    this.password = password;
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    restTemplate = new RestTemplate();
    //oAuth2ClientContext = new DefaultOAuth2ClientContext();
}

@Override
public void apply(RequestTemplate template) {
    // demander un token à keycloak et le joindre à la request
    Optional<String> token = getToken();
    if (token.isPresent()) {
        template.header(HttpHeaders.ORIGIN, "localhost");
        template.header(AUTHORIZATION, String.format("%s %s", BEARER, token.get()));
    }
}

private Optional<String> getToken() {
    if (oAuth2ClientContext.getAccessToken() == null || oAuth2ClientContext.getAccessToken().isExpired()) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", this.clientId);
        map.add("client_secret", this.clientSecret);
        map.add("grant_type", "password"); // client_credentials //password
        map.add("username", this.user);
        map.add("password", this.password);
        oAuth2ClientContext.setAccessToken(askToken(map));
    } 
    
    if (oAuth2ClientContext.getAccessToken() != null){
        return Optional.ofNullable(oAuth2ClientContext.getAccessToken().getValue());
    } else {
        return Optional.empty();
    }
}

private CustomOAuth2AccessToken askToken( MultiValueMap<String, String> map) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        ResponseEntity<CustomOAuth2AccessToken> response = restTemplate.postForEntity(
                this.authUrl, request, CustomOAuth2AccessToken.class);
        
        if (response != null && response.hasBody()) {
            return response.getBody();
        } else {
            return null;
        }
}

}

And finally the ressource :

    @RestController
@RequestMapping("/api")
public class DocumentResource {

        private static String TMP_FILE_PREFIX = "smartdoc_tmp";

        public DocumentResource() {
        }

        @GetMapping("/ebox/test")
        public ResponseEntity<HasEboxResponse> test() {
                return ResponseEntity.ok(new HasEboxResponse());
        }

        @PostMapping("/ebox/test")
        public ResponseEntity<HasEboxResponse> testPost(@RequestBody HasEboxRequest request) {
                return ResponseEntity.ok(new HasEboxResponse());
        }

        @PutMapping("/ebox/test")
        public ResponseEntity<HasEboxResponse> testPut(@RequestBody HasEboxRequest request) {
                return ResponseEntity.ok(new HasEboxResponse());
        }

}

Thanks !


Solution

  • The problem was in the spring security config. WebSecurity didn't allow to call urls like "[SERVICE_NAME]/api" without authentication. I added a rule to allow acces to some urls. If an access token is in the header, it will be forward to the service by zuul.

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
            .antMatchers("/ext/*/api/**") // allow calls to services, redirect by zuul
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/i18n/**")
            .antMatchers("/content/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }
    

    In order to call others services by UI and let inject access token by the gateway, I defined two groups of routes in my zuul config,

    routes:
        myservice: 
            path: /myservice/**
            serviceId: myservice
        myservice_ext: 
            path: /ext/myservice/**
            serviceId: myservice 
    
    • /ext/myService... : referencing services and don't and ignore by spring secu
    • /myService... : referencing services but handled by spring secu