Skip to content

Force "application/json" in Http Accept header #1489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 83 additions & 76 deletions openid-connect-client/pom.xml
Original file line number Diff line number Diff line change
@@ -1,76 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2018 The MIT Internet Trust Consortium

Portions copyright 2011-2013 The MITRE Corporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>openid-connect-parent</artifactId>
<groupId>org.mitre</groupId>
<version>1.3.4-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>openid-connect-client</artifactId>
<description>OpenID Connect Client filter for Spring Security</description>
<name>OpenID Connect Client</name>
<dependencies>
<dependency>
<groupId>org.mitre</groupId>
<artifactId>openid-connect-common</artifactId>
</dependency>
</dependencies>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<!-- BUILD SOURCE FILES -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- BUILD JavaDoc FILES -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2018 The MIT Internet Trust Consortium

Portions copyright 2011-2013 The MITRE Corporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>openid-connect-parent</artifactId>
<groupId>org.mitre</groupId>
<version>1.3.4-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<artifactId>openid-connect-client</artifactId>
<description>OpenID Connect Client filter for Spring Security</description>
<name>OpenID Connect Client</name>
<dependencies>
<dependency>
<groupId>org.mitre</groupId>
<artifactId>openid-connect-common</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.9</version>
<scope>test</scope>
</dependency>
</dependencies>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<!-- BUILD SOURCE FILES -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- BUILD JavaDoc FILES -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.io.IOException;
import java.net.URI;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
Expand All @@ -36,7 +37,11 @@
import org.mitre.oauth2.model.RegisteredClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.core.Authentication;
Expand Down Expand Up @@ -309,7 +314,12 @@ protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOE
form.add("token", accessToken);

try {
validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

ResponseEntity<String> response = restTemplate.exchange(introspectionUrl, HttpMethod.POST, new HttpEntity<>(form, headers), String.class);
validatedToken = response.getBody();
} catch (RestClientException rce) {
logger.error("validateToken", rce);
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import static org.mitre.util.JsonUtils.getAsString;
import static org.mitre.util.JsonUtils.getAsStringList;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
Expand All @@ -37,6 +38,11 @@
import org.mitre.openid.connect.config.ServerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.web.client.RestTemplate;
Expand Down Expand Up @@ -141,15 +147,18 @@ private class OpenIDConnectServiceConfigurationFetcher extends CacheLoader<Strin
@Override
public ServerConfiguration load(String issuer) throws Exception {
RestTemplate restTemplate = new RestTemplate(httpFactory);

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

// data holder
ServerConfiguration conf = new ServerConfiguration();

// construct the well-known URI
String url = issuer + "/.well-known/openid-configuration";

// fetch the value
String jsonString = restTemplate.getForObject(url, String.class);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
String jsonString = response.getBody();

JsonElement parsed = parser.parse(jsonString);
if (parsed.isJsonObject()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package org.mitre.oauth2.introspectingfilter;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mitre.oauth2.introspectingfilter.service.IntrospectionConfigurationService;
import org.mitre.oauth2.introspectingfilter.service.impl.JWTParsingIntrospectionConfigurationService;
import org.mitre.oauth2.introspectingfilter.service.impl.StaticIntrospectionConfigurationService;
import org.mitre.oauth2.model.RegisteredClient;
import org.mitre.openid.connect.client.service.impl.DynamicServerConfigurationService;
import org.mitre.openid.connect.config.ServerConfiguration;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

/**
* @author Loic Gangloff
*
*/
@RunWith(MockitoJUnitRunner.class)
public class TestIntrospectingTokenService {


private IntrospectingTokenService service;

private String introspectionUrl = "http://www.example.com";
private RegisteredClient client = new RegisteredClient();

private String json = "{\"active\":true,\"scope\":\"sub openid profile\",\"exp\":1591344840,\"sub\":\"[email protected]\",\"username\":\"[email protected]\",\"expires_at\":\"2020-06-05T10:14:00+0200\",\"client_id\":\"a-client-id\",\"token_type\":\"Bearer\"}";

private String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<introspectResponse>" +
"<active>true</active>" +
"<client_id>a-client-id</client_id>" +
"<exp>1591344840</exp>n" +
"<expires_at>2020-06-05T10:14:00+0200</expires_at>" +
"<scope>sub openid profile</scope>" +
"<sub>[email protected]</sub>" +
"<token_type>Bearer</token_type>" +
"<username>[email protected]</username>"
+ "</introspectResponse>";

@Mock
private HttpClient mockHttpClient;

@Before
public void prepare() {
client.setClientId("a-client-id");
client.setClientSecret("a-client-secret");

StaticIntrospectionConfigurationService introspectionConfig = new StaticIntrospectionConfigurationService();
introspectionConfig.setClientConfiguration(client);
introspectionConfig.setIntrospectionUrl(introspectionUrl);

service = new IntrospectingTokenService(mockHttpClient);
service.setIntrospectionConfigurationService(introspectionConfig);
}


@Test
public void resttemplate_must_have_xml_accept_header() throws IOException {

HttpResponse response = Mockito.mock(HttpResponse.class);
StatusLine statusLine = Mockito.mock(StatusLine.class);
Mockito.when(statusLine.getStatusCode()).thenReturn(200);
Mockito.when(response.getAllHeaders()).thenReturn(new Header[] {});
Mockito.when(response.getStatusLine()).thenReturn(statusLine);
Mockito.when(response.getEntity()).thenReturn(new StringEntity(json));
Mockito.when(mockHttpClient.execute(Mockito.any(), (HttpContext) Mockito.any())).thenReturn(response);

RestTemplate restemplate = Mockito.spy(new RestTemplate(new HttpComponentsClientHttpRequestFactory(mockHttpClient)));

restemplate.postForObject(introspectionUrl, "a-token", String.class);

ArgumentCaptor<HttpPost> argument = ArgumentCaptor.forClass(HttpPost.class);
Mockito.verify(mockHttpClient).execute(argument.capture(), (HttpContext) Mockito.any());


Header acceptHeader = argument.getValue().getFirstHeader("Accept");
List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader.getValue());

assertThat(mediaTypes, hasItem(MediaType.APPLICATION_JSON));
assertThat(mediaTypes, hasItem(MediaType.APPLICATION_XML));

}

@Test
public void introspectingtokenservice_must_not_have_xml_accept_header() throws IOException {

HttpResponse response = Mockito.mock(HttpResponse.class);
StatusLine statusLine = Mockito.mock(StatusLine.class);
Mockito.when(statusLine.getStatusCode()).thenReturn(200);
Mockito.when(response.getAllHeaders()).thenReturn(new Header[] {});
Mockito.when(response.getStatusLine()).thenReturn(statusLine);
Mockito.when(response.getEntity()).thenReturn(new StringEntity(json));
Mockito.when(mockHttpClient.execute(Mockito.any(), (HttpContext) Mockito.any())).thenReturn(response);

OAuth2Authentication result = service.loadAuthentication("a-token");

ArgumentCaptor<HttpPost> argument = ArgumentCaptor.forClass(HttpPost.class);
Mockito.verify(mockHttpClient).execute(argument.capture(), (HttpContext) Mockito.any());


Header acceptHeader = argument.getValue().getFirstHeader("Accept");
List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader.getValue());

assertThat(mediaTypes, hasItem(MediaType.APPLICATION_JSON));
assertThat(mediaTypes, not(hasItem(MediaType.APPLICATION_XML)));

}

}
Loading