spring mvc rest service redirect / forward / proxy

后端 未结 6 1484
南旧
南旧 2020-11-27 12:02

I have build a web application using spring mvc framework to publish REST services. For example:

@Controller
@RequestMapping(\"/movie\")
public class MovieCo         


        
6条回答
  •  半阙折子戏
    2020-11-27 12:31

    proxy controller with oauth2

    @RequestMapping("v9")
    @RestController
    @EnableConfigurationProperties
    public class ProxyRestController {
        Logger logger = LoggerFactory.getLogger(this.getClass());
    
        @Autowired
        OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails;
    
        @Autowired
        private ClientCredentialsResourceDetails clientCredentialsResourceDetails;
    
        @Autowired
        OAuth2RestTemplate oAuth2RestTemplate;
    
    
        @Value("${gateway.url:http://gateway/}")
        String gatewayUrl;
    
        @RequestMapping(value = "/proxy/**")
        public String proxy(@RequestBody(required = false) String body, HttpMethod method, HttpServletRequest request, HttpServletResponse response,
                            @RequestHeader HttpHeaders headers) throws ServletException, IOException, URISyntaxException {
    
            body = body == null ? "" : body;
            String path = request.getRequestURI();
            String query = request.getQueryString();
            path = path.replaceAll(".*/v9/proxy", "");
            StringBuffer urlBuilder = new StringBuffer(gatewayUrl);
            if (path != null) {
                urlBuilder.append(path);
            }
            if (query != null) {
                urlBuilder.append('?');
                urlBuilder.append(query);
            }
            URI url = new URI(urlBuilder.toString());
            if (logger.isInfoEnabled()) {
                logger.info("url: {} ", url);
                logger.info("method: {} ", method);
                logger.info("body: {} ", body);
                logger.info("headers: {} ", headers);
            }
            ResponseEntity responseEntity
                    = oAuth2RestTemplate.exchange(url, method, new HttpEntity(body, headers), String.class);
            return responseEntity.getBody();
        }
    
    
        @Bean
        @ConfigurationProperties("security.oauth2.client")
        @ConditionalOnMissingBean(ClientCredentialsResourceDetails.class)
        public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
            return new ClientCredentialsResourceDetails();
        }
    
        @Bean
        @ConditionalOnMissingBean
        public OAuth2RestTemplate oAuth2RestTemplate() {
            return new OAuth2RestTemplate(clientCredentialsResourceDetails);
        }
    
    
    

提交回复
热议问题