Search in sources :

Example 11 with MultiValueMap

use of org.springframework.util.MultiValueMap in project spring-security-oauth by spring-projects.

the class ClientCredentialsProviderTests method testHardCodedAuthenticationWrongClient.

@Test
public void testHardCodedAuthenticationWrongClient() {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("grant_type", "client_credentials");
    params.add("client_id", "my-trusted-client");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    RequestEntity<MultiValueMap<String, String>> req = new RequestEntity<MultiValueMap<String, String>>(params, headers, HttpMethod.POST, tokenUri);
    try {
        restTemplate.exchange(req, Map.class);
        fail("Expected HTTP 401");
    } catch (HttpStatusCodeException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) RequestEntity(org.springframework.http.RequestEntity) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Test(org.junit.Test)

Example 12 with MultiValueMap

use of org.springframework.util.MultiValueMap in project spring-security-oauth by spring-projects.

the class ClientCredentialsProviderTests method testHardCodedAuthenticationFineClient.

/**
	 * No Basic authentication provided, only the hard coded client_id.
	 */
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testHardCodedAuthenticationFineClient() {
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("grant_type", "client_credentials");
    params.add("client_id", "my-client-with-secret");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    RequestEntity<MultiValueMap<String, String>> req = new RequestEntity<MultiValueMap<String, String>>(params, headers, HttpMethod.POST, tokenUri);
    ResponseEntity<Map> response = restTemplate.exchange(req, Map.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    Map<String, String> body = response.getBody();
    String accessToken = body.get("access_token");
    assertNotNull(accessToken);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) RequestEntity(org.springframework.http.RequestEntity) MultiValueMap(org.springframework.util.MultiValueMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Test(org.junit.Test)

Example 13 with MultiValueMap

use of org.springframework.util.MultiValueMap 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 14 with MultiValueMap

use of org.springframework.util.MultiValueMap in project cas by apereo.

the class ClickatellSmsSender method send.

@Override
public boolean send(final String from, final String to, final String message) {
    try {
        final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", this.token);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        final Map<String, Object> map = new HashMap<>();
        map.put("content", message);
        map.put("to", Arrays.asList(to));
        map.put("from", from);
        final StringWriter stringify = new StringWriter();
        mapper.writeValue(stringify, map);
        final HttpEntity<String> request = new HttpEntity<>(stringify.toString(), headers);
        final ResponseEntity<Map> response = restTemplate.postForEntity(new URI(this.serverUrl), request, Map.class);
        if (response.hasBody()) {
            final List<Map> messages = (List<Map>) response.getBody().get("messages");
            final String error = (String) response.getBody().get("error");
            if (StringUtils.isNotBlank(error)) {
                LOGGER.error(error);
                return false;
            }
            final List<String> errors = messages.stream().filter(m -> m.containsKey("accepted") && !Boolean.valueOf(m.get("accepted").toString()) && m.containsKey("error")).map(m -> (String) m.get("error")).collect(Collectors.toList());
            if (errors.isEmpty()) {
                return true;
            }
            errors.forEach(LOGGER::error);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return false;
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) MediaType(org.springframework.http.MediaType) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) HttpEntity(org.springframework.http.HttpEntity) List(java.util.List) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) Map(java.util.Map) ResponseEntity(org.springframework.http.ResponseEntity) URI(java.net.URI) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) SmsSender(org.apereo.cas.util.io.SmsSender) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) URI(java.net.URI) StringWriter(java.io.StringWriter) List(java.util.List) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 15 with MultiValueMap

use of org.springframework.util.MultiValueMap in project spring-security-oauth by spring-projects.

the class AbstractRefreshTokenSupportTests method getAccessToken.

private OAuth2AccessToken getAccessToken(String scope, String clientId) throws Exception {
    MultiValueMap<String, String> formData = getTokenFormData(scope, clientId);
    HttpHeaders headers = getTokenHeaders(clientId);
    @SuppressWarnings("rawtypes") ResponseEntity<Map> response = http.postForMap(tokenPath(), headers, formData);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertTrue("Wrong cache control: " + response.getHeaders().getFirst("Cache-Control"), response.getHeaders().getFirst("Cache-Control").contains("no-store"));
    @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
    return accessToken;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) MultiValueMap(org.springframework.util.MultiValueMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Aggregations

MultiValueMap (org.springframework.util.MultiValueMap)46 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)33 Test (org.junit.Test)18 Map (java.util.Map)17 HttpHeaders (org.springframework.http.HttpHeaders)17 List (java.util.List)9 HttpEntity (org.springframework.http.HttpEntity)9 RestTemplate (org.springframework.web.client.RestTemplate)6 URI (java.net.URI)4 LinkedHashMap (java.util.LinkedHashMap)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)4 HttpRequestHandler (org.springframework.web.HttpRequestHandler)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Link (org.apache.geode.management.internal.web.domain.Link)3 UnitTest (org.apache.geode.test.junit.categories.UnitTest)3 MethodParameter (org.springframework.core.MethodParameter)3 DefaultHandshakeHandler (org.springframework.web.socket.server.support.DefaultHandshakeHandler)3 HttpSessionHandshakeInterceptor (org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor)3