Search in sources :

Example 96 with MediaType

use of org.springframework.http.MediaType in project spring-security by spring-projects.

the class OAuth2AuthorizationGrantRequestEntityUtils method getDefaultTokenRequestHeaders.

private static HttpHeaders getDefaultTokenRequestHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
    final MediaType contentType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
    headers.setContentType(contentType);
    return headers;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType)

Example 97 with MediaType

use of org.springframework.http.MediaType in project spring-security by spring-projects.

the class NimbusJwtDecoderTests method decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson.

// gh-7290
@Test
public void decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson() {
    RestOperations restOperations = mock(RestOperations.class);
    given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
    // @formatter:off
    JWTProcessor<SecurityContext> processor = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor();
    // @formatter:on
    NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor);
    jwtDecoder.decode(SIGNED_JWT);
    ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
    verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
    List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
    assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
Also used : SecurityContext(com.nimbusds.jose.proc.SecurityContext) MediaType(org.springframework.http.MediaType) RestOperations(org.springframework.web.client.RestOperations) RequestEntity(org.springframework.http.RequestEntity) Test(org.junit.jupiter.api.Test)

Example 98 with MediaType

use of org.springframework.http.MediaType in project spring-security by spring-projects.

the class NimbusReactiveOpaqueTokenIntrospector method adaptToNimbusResponse.

private Mono<HTTPResponse> adaptToNimbusResponse(ClientResponse responseEntity) {
    MediaType contentType = responseEntity.headers().contentType().orElseThrow(() -> {
        this.logger.trace("Did not receive Content-Type from introspection endpoint in response");
        return new OAuth2IntrospectionException("Introspection endpoint response was invalid, as no Content-Type header was provided");
    });
    // Nimbus expects JSON, but does not appear to validate this header first.
    if (!contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
        this.logger.trace("Did not receive JSON-compatible Content-Type from introspection endpoint in response");
        throw new OAuth2IntrospectionException("Introspection endpoint response was invalid, as content type '" + contentType + "' is not compatible with JSON");
    }
    HTTPResponse response = new HTTPResponse(responseEntity.rawStatusCode());
    response.setHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
    if (response.getStatusCode() != HTTPResponse.SC_OK) {
        this.logger.trace("Introspection endpoint returned non-OK status code");
        // @formatter:off
        return responseEntity.bodyToFlux(DataBuffer.class).map(DataBufferUtils::release).then(Mono.error(new OAuth2IntrospectionException("Introspection endpoint responded with HTTP status code " + response.getStatusCode())));
    // @formatter:on
    }
    return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map((body) -> response);
}
Also used : HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) MediaType(org.springframework.http.MediaType)

Example 99 with MediaType

use of org.springframework.http.MediaType in project spring-security by spring-projects.

the class MediaTypeServerWebExchangeMatcher method resolveMediaTypes.

private List<MediaType> resolveMediaTypes(ServerWebExchange exchange) throws NotAcceptableStatusException {
    try {
        List<MediaType> mediaTypes = exchange.getRequest().getHeaders().getAccept();
        MediaType.sortBySpecificityAndQuality(mediaTypes);
        return mediaTypes;
    } catch (InvalidMediaTypeException ex) {
        String value = exchange.getRequest().getHeaders().getFirst("Accept");
        throw new NotAcceptableStatusException("Could not parse 'Accept' header [" + value + "]: " + ex.getMessage());
    }
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) MediaType(org.springframework.http.MediaType) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 100 with MediaType

use of org.springframework.http.MediaType in project spring-security by spring-projects.

the class MediaTypeServerWebExchangeMatcher method matches.

@Override
public Mono<MatchResult> matches(ServerWebExchange exchange) {
    List<MediaType> httpRequestMediaTypes;
    try {
        httpRequestMediaTypes = resolveMediaTypes(exchange);
    } catch (NotAcceptableStatusException ex) {
        this.logger.debug("Failed to parse MediaTypes, returning false", ex);
        return MatchResult.notMatch();
    }
    this.logger.debug(LogMessage.format("httpRequestMediaTypes=%s", httpRequestMediaTypes));
    for (MediaType httpRequestMediaType : httpRequestMediaTypes) {
        this.logger.debug(LogMessage.format("Processing %s", httpRequestMediaType));
        if (shouldIgnore(httpRequestMediaType)) {
            this.logger.debug("Ignoring");
            continue;
        }
        if (this.useEquals) {
            boolean isEqualTo = this.matchingMediaTypes.contains(httpRequestMediaType);
            this.logger.debug("isEqualTo " + isEqualTo);
            return isEqualTo ? MatchResult.match() : MatchResult.notMatch();
        }
        for (MediaType matchingMediaType : this.matchingMediaTypes) {
            boolean isCompatibleWith = matchingMediaType.isCompatibleWith(httpRequestMediaType);
            this.logger.debug(LogMessage.format("%s .isCompatibleWith %s = %s", matchingMediaType, httpRequestMediaType, isCompatibleWith));
            if (isCompatibleWith) {
                return MatchResult.match();
            }
        }
    }
    this.logger.debug("Did not match any media types");
    return MatchResult.notMatch();
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) MediaType(org.springframework.http.MediaType)

Aggregations

MediaType (org.springframework.http.MediaType)477 Test (org.junit.jupiter.api.Test)177 HttpHeaders (org.springframework.http.HttpHeaders)97 Test (org.junit.Test)61 ArrayList (java.util.ArrayList)58 Charset (java.nio.charset.Charset)42 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)34 List (java.util.List)33 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)33 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)33 HashMap (java.util.HashMap)30 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)30 IOException (java.io.IOException)26 Resource (org.springframework.core.io.Resource)23 ResolvableType (org.springframework.core.ResolvableType)22 HttpEntity (org.springframework.http.HttpEntity)21 ServerWebExchange (org.springframework.web.server.ServerWebExchange)20 MockServerWebExchange (org.springframework.web.testfixture.server.MockServerWebExchange)20 Nullable (org.springframework.lang.Nullable)18 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)18