How to access Spring REST API in JHipster with Spring RestTemplate

十年热恋 提交于 2019-12-11 04:06:22

问题


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.

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

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

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.


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/29096595/how-to-access-spring-rest-api-in-jhipster-with-spring-resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!