mercoledì 21 ottobre 2020
JWT token based REST API
@Data
public class JWTData {
String accessToken;
long expiresIn;
String tokenType;
String scope;
}
------------------------------------------------------------------------------------------------------------
public void sendRequest() throws Exception {
final String jwturi = "http://someurl";
RestTemplate JWTRestTemplate = new RestTemplate();
HttpHeaders tokenheaders = new HttpHeaders();
tokenheaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> jwtParameters= new LinkedMultiValueMap<>();
jwtParameters.add("grant_type", "client_credentials");
jwtParameters.add("client_id", "jwtClientId");
jwtParameters.add("client_secret", "jwtClientSecret");
HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(jwtParameters, tokenheaders);
ResponseEntity<JWTData> response = JWTRestTemplate.postForEntity(jwturi, tokenRequest , JWTData.class);
log.info("\n\n-- JWT RESPONSE BODY: {} ", response.getBody().toString());
String JWT = response.getBody().getAccessToken();
log.info("access token: " + JWT);
String alertDataAsString = jsonMapper.writeValueAsString(alertData);
final String uri = alarmNotificationUrl;
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new MyRestErrorHandler());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer access_token"+ JWT);
log.info("Json sent: " + alertDataAsString);
HttpEntity<?> request = new HttpEntity<Object>(alertDataAsString, headers);
ResponseEntity<Object> responseAsString = restTemplate.exchange(uri, HttpMethod.POST, request, Object.class);
log.info("\n\n-- RESPONSE STATUS CODE: {} ", responseAsString.getStatusCode());
log.info("\n\n-- RESPONSE BODY: {} ", responseAsString.getBody().toString());
}
------------------------------------------------------------------------------------------------------------
@Slf4j
public class MyRestErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
log.info("Errore in chiamata agli endpoint");
}
}
Iscriviti a:
Commenti sul post (Atom)
How to deploy Podman images to OpenShift Container Platform (CRC on localhost)
I have a microservice on localhost and I want to deploy its Podman image on OCP, which I am running using CRC on localhost. 1. Get the...
-
Precondizione: La precondizione di un metodo e' una condizione che deve essere verificata prima che quel metodo sia invocato. Le preco...
-
My intent is to configure SSO on Keycloak and Liferay. I have createad a docker-compose environment with Keycloak: #####################...
Nessun commento:
Posta un commento