How to access Spring REST API in JHipster with Spr

2019-07-21 04:19发布

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条回答
三岁会撩人
2楼-- · 2019-07-21 04:38

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.

查看更多
登录 后发表回答