001/* 002 * Licensed under the Apache License, Version 2.0 (the "License"); 003 * you may not use this file except in compliance with the License. 004 * You may obtain a copy of the License at 005 * 006 * http://www.apache.org/licenses/LICENSE-2.0 007 * 008 * Unless required by applicable law or agreed to in writing, software 009 * distributed under the License is distributed on an "AS IS" BASIS, 010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 011 * See the License for the specific language governing permissions and 012 * limitations under the License. 013 */ 014package org.gbif.ws.remoteauth; 015 016import java.time.Duration; 017 018import org.springframework.boot.web.client.RestTemplateBuilder; 019import org.springframework.http.HttpEntity; 020import org.springframework.http.HttpHeaders; 021import org.springframework.http.ResponseEntity; 022import org.springframework.security.authentication.BadCredentialsException; 023import org.springframework.web.client.HttpClientErrorException; 024import org.springframework.web.client.RestClientException; 025import org.springframework.web.client.RestTemplate; 026 027/** 028 * Implementation of a {@link RemoteAuthClient} by using {@link RestTemplate} as client. 029 */ 030public class RestTemplateRemoteAuthClient implements RemoteAuthClient { 031 032 private final RestTemplate restTemplate; 033 034 public RestTemplateRemoteAuthClient(RestTemplate restTemplate) { 035 this.restTemplate = restTemplate; 036 } 037 038 @Override 039 public ResponseEntity<String> remoteAuth(String path, HttpHeaders headers) { 040 try { 041 return restTemplate.postForEntity(path, new HttpEntity<>(headers), String.class); 042 } catch (HttpClientErrorException.Unauthorized 043 | HttpClientErrorException.Forbidden 044 | HttpClientErrorException.BadRequest e) { 045 throw new BadCredentialsException("Wrong credentials for user", e); 046 } catch (Exception e) { 047 throw new RestClientException("Could not authenticate user", e); 048 } 049 } 050 051 public static RestTemplateRemoteAuthClient createInstance( 052 RestTemplateBuilder builder, String gbifApiUrl) { 053 return new RestTemplateRemoteAuthClient( 054 builder 055 .setConnectTimeout(Duration.ofSeconds(30)) 056 .setReadTimeout(Duration.ofSeconds(60)) 057 .rootUri(gbifApiUrl) 058 .build()); 059 } 060}