Search in sources :

Example 71 with HttpHeaders

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);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) TestRestTemplate(org.springframework.boot.test.web.client.TestRestTemplate) JsonNode(com.fasterxml.jackson.databind.JsonNode)

Example 72 with HttpHeaders

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;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders)

Example 73 with HttpHeaders

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);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) URI(java.net.URI) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) ResponseEntity(org.springframework.http.ResponseEntity) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 74 with HttpHeaders

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;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) PasswordManagementProperties(org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential)

Example 75 with HttpHeaders

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);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Test(org.junit.Test)

Aggregations

HttpHeaders (org.springframework.http.HttpHeaders)1676 Test (org.junit.Test)426 ResponseEntity (org.springframework.http.ResponseEntity)383 HttpEntity (org.springframework.http.HttpEntity)345 Test (org.junit.jupiter.api.Test)273 HashMap (java.util.HashMap)184 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)154 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)127 MediaType (org.springframework.http.MediaType)121 URI (java.net.URI)111 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)102 Map (java.util.Map)97 IOException (java.io.IOException)83 RestTemplate (org.springframework.web.client.RestTemplate)78 ArrayList (java.util.ArrayList)75 MessageHeaders (org.springframework.messaging.MessageHeaders)74 MultiValueMap (org.springframework.util.MultiValueMap)74 HttpStatus (org.springframework.http.HttpStatus)71 List (java.util.List)65 Timed (com.codahale.metrics.annotation.Timed)54