making / from-zero-to-hero-with-rest-and-oauth2

47 stars 8 forks source link

Invoking REST endpoint with Ajax working fine but not working with OAuth2RestTemplate #1

Open sivaprasadreddy opened 6 years ago

sivaprasadreddy commented 6 years ago

Hi, In UI Zuul Proxy, the endpoint /api/messages is invoked using Ajax which is working fine. But if I want to invoke the same endpoint (/api/messages) using OAuth2RestTemplate from a Controller in UI application it is giving Login page HTML response. Any reason why it is redirecting to Login page?

making commented 6 years ago

Can you share code of what you're trying to do?

sivaprasadreddy commented 6 years ago

I have registered OAuth2RestTemplate bean in UIApplication.

@Bean
public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails resourceDetails) {
  OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resourceDetails, oAuth2ClientContext);
  return oAuth2RestTemplate;
}

In ZuulProxy(UI) application.properties registered the catalog-service routes.

zuul.routes.catalog-service.path=/catalog/**
zuul.routes.catalog-service.url=http://localhost:8181/catalog/

In ZuulProxy UI application, I have a controller from which I am trying to invoke catalog-service thru proxy URL as follows:


@Controller
public class HomeController 
{
    @Autowired
    OAuth2RestTemplate restTemplate;

    @GetMapping("/")
    public String index(Model model)
    {
        ResponseEntity<String> productResp = restTemplate.getForEntity("http://localhost:8080/ui/catalog/products", String.class);

        return "index";
    }
}

But the productResp body contains the login page HTML.

But if I use direct catalog-service endpoint URL http://localhost:8181/catalog/products then it is working fine.

PS: Assume catalog-service is similar to resource server in the repository and /catalog/products endpoint is similar to /api/messages.

making commented 6 years ago

Are you using spring-cloud-security that has token relay functionaries? https://github.com/spring-projects/spring-security/wiki/OAuth-2.0-Features-Matrix

sivaprasadreddy commented 6 years ago

Yes, I am using spring-cloud-security. Here is my code repository https://github.com/sivaprasadreddy/spring-security-oauth2-demo

The code (commented) that is not working is in https://github.com/sivaprasadreddy/spring-security-oauth2-demo/blob/master/ui-zuul-app/src/main/java/com/sivalabs/uizuulapp/HomeController.java.

But the same endpoint is working fine thru AJAX https://github.com/sivaprasadreddy/spring-security-oauth2-demo/blob/master/ui-zuul-app/src/main/resources/templates/index.html.