如何使用Spring RestTemplate在JHipster中访问Spring REST API [英] How to access Spring REST API in JHipster with Spring RestTemplate

查看:91
本文介绍了如何使用Spring RestTemplate在JHipster中访问Spring REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在JHipster的首页上对某些实体进行了设置. AngularJS的前端效果很好,API页面也很出色,让我可以按预期测试我的服务.

I have set up JHipster like described on its homepage with some entities. Frontend with AngularJS works great and also the API page, lets me test my services as expected.

现在,我正在尝试使用Spring的RestTemplate这样编写REST-Client:

Now I am trying to write a REST-Client using Spring's RestTemplate like this:

public List<SomeEntity> getAllEntities(){
     URI uri = URI.create("http://localhost:8080/api/entities");
     HttpHeaders httpHeaders = this.createHeaders("admin", "admin")
     ResponseEntity<SomeEntity[]> responseEntity =  restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<SomeEntity>(httpHeaders), SomeEntity[].class);
     return Arrays.asList(responseEntity.getBody());
}


private HttpHeaders createHeaders(final String username, final String password ){
HttpHeaders headers =  new HttpHeaders(){
      {
         String auth = username + ":" + password;
         byte[] encodedAuth = Base64.encode(
            auth.getBytes(Charset.forName("US-ASCII")) );
         String authHeader = "Basic " + new String( encodedAuth );
         set( "Authorization", authHeader );
      }
   };
   headers.add("Content-Type", "application/json");
   headers.add("Accept", "application/json");

   return headers;
}

但这会导致以下错误: [WARN] org.springframework.web.client.RestTemplate-GET请求" http://localhost:8080/api/实体"显示为401(未授权);调用错误处理程序

But this results in the following error: [WARN] org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/api/entities" resulted in 401 (Unauthorized); invoking error handler

现在我不确定,是否以及如何调整我的HttpHeaders,或者我简单的基本身份验证处理方法是否完全错误.

Now I am not sure, if and how I need to adapt my HttpHeaders or if my simple basic-auth handling approach at all is wrong.

推荐答案

您的身份验证方式是错误的,似乎您在生成应用程序时选择了会话身份验证,因此这需要基于表单的身份验证而不是http basic身份验证,并且需要能够存储会话cookie和CSRF cookie,因此很可能使用commons http客户端.

The way you authenticate is wrong, it seems you chose session authentication when generating your app, so this requires form-based auth not http basic auth and it requires being able to store session cookie and CSRF cookie so most likely using commons http client.

也许在生成应用程序时选择xauth令牌身份验证会更简单.

Maybe choosing xauth token authentication when generating your app would be simpler.

一旦成功,客户端将不会与JHipster应用程序在同一主机上运行,​​就会遇到CORS问题.

Once you get this working you will have CORS issues as soon as your client won't run on same host as your JHipster app.

这篇关于如何使用Spring RestTemplate在JHipster中访问Spring REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆