use of org.springframework.http.HttpHeaders in project spring-boot by spring-projects.
the class OAuth2AutoConfigurationTests method verifyAuthentication.
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
String baseUrl = "http://localhost:" + this.context.getWebServer().getPort();
TestRestTemplate rest = new TestRestTemplate();
// First, verify the web endpoint can't be reached
assertEndpointUnauthorized(baseUrl, rest);
// Since we can't reach it, need to collect an authorization token
HttpHeaders headers = getHeaders(config);
String url = baseUrl + "/oauth/token";
JsonNode tokenResponse = rest.postForObject(url, new HttpEntity<>(getBody(), headers), JsonNode.class);
String authorizationToken = tokenResponse.findValue("access_token").asText();
String tokenType = tokenResponse.findValue("token_type").asText();
String scope = tokenResponse.findValues("scope").get(0).toString();
assertThat(tokenType).isEqualTo("bearer");
assertThat(scope).isEqualTo("\"read\"");
// Now we should be able to see that endpoint.
headers.set("Authorization", "BEARER " + authorizationToken);
ResponseEntity<String> securedResponse = rest.exchange(new RequestEntity<Void>(headers, HttpMethod.GET, URI.create(baseUrl + "/securedFind")), String.class);
assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(securedResponse.getBody()).isEqualTo("You reached an endpoint " + "secured by Spring Security OAuth2");
ResponseEntity<String> entity = rest.exchange(new RequestEntity<Void>(headers, HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class);
assertThat(entity.getStatusCode()).isEqualTo(finalStatus);
}
use of org.springframework.http.HttpHeaders in project spring-boot by spring-projects.
the class OAuth2AutoConfigurationTests method getHeaders.
private HttpHeaders getHeaders(ClientDetails config) {
HttpHeaders headers = new HttpHeaders();
String token = new String(Base64.encode((config.getClientId() + ":" + config.getClientSecret()).getBytes()));
headers.set("Authorization", "Basic " + token);
return headers;
}
use of org.springframework.http.HttpHeaders in project cas by apereo.
the class TicketsResource method createTicketGrantingTicket.
/**
* Create new ticket granting ticket.
*
* @param requestBody username and password application/x-www-form-urlencoded values
* @param request raw HttpServletRequest used to call this method
* @return ResponseEntity representing RESTful response
* @throws JsonProcessingException in case of JSON parsing failure
*/
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) throws JsonProcessingException {
try {
final Credential credential = this.credentialFactory.fromRequestBody(requestBody);
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, credential);
final TicketGrantingTicket tgtId = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(ticketReference);
headers.setContentType(MediaType.TEXT_HTML);
final String tgtUrl = ticketReference.toString();
final String response = new StringBuilder(SUCCESSFUL_TGT_CREATED_INITIAL_LENGTH + tgtUrl.length()).append(DOCTYPE_AND_OPENING_FORM).append(tgtUrl).append(REST_OF_THE_FORM_AND_CLOSING_TAGS).toString();
return new ResponseEntity<>(response, headers, HttpStatus.CREATED);
} catch (final AuthenticationException e) {
final List<String> authnExceptions = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.toList());
final Map<String, List<String>> errorsMap = new HashMap<>();
errorsMap.put("authentication_exceptions", authnExceptions);
LOGGER.error("[{}] Caused by: [{}]", e.getMessage(), authnExceptions, e);
try {
return new ResponseEntity<>(this.jacksonPrettyWriter.writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
} catch (final JsonProcessingException exception) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (final BadRequestException e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Throwable e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
use of org.springframework.http.HttpHeaders in project cas by apereo.
the class RestPasswordManagementService method change.
@Override
public boolean change(final Credential c, final PasswordChangeBean bean) {
final PasswordManagementProperties.Rest rest = passwordManagementProperties.getRest();
if (StringUtils.isBlank(rest.getEndpointUrlChange())) {
return false;
}
final UsernamePasswordCredential upc = (UsernamePasswordCredential) c;
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.put("username", Arrays.asList(upc.getUsername()));
headers.put("password", Arrays.asList(bean.getPassword()));
headers.put("oldPassword", Arrays.asList(upc.getPassword()));
final HttpEntity<String> entity = new HttpEntity<>(headers);
final ResponseEntity<Boolean> result = restTemplate.exchange(rest.getEndpointUrlEmail(), HttpMethod.POST, entity, Boolean.class);
if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
return result.getBody();
}
return false;
}
use of org.springframework.http.HttpHeaders in project spring-security-oauth by spring-projects.
the class OAuth2AccessTokenSupportTests method testRetrieveTokenFormEncoded.
@Test
public void testRetrieveTokenFormEncoded() throws Exception {
// SECOAUTH-306: no need to set message converters
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
response.setBody("access_token=FOO");
response.setHeaders(responseHeaders);
OAuth2AccessToken retrieveToken = support.retrieveToken(request, resource, form, requestHeaders);
assertEquals(accessToken, retrieveToken);
}
Aggregations