Skip to content

Commit

Permalink
feat(openid): Initial implementation of UserInfo policy
Browse files Browse the repository at this point in the history
  • Loading branch information
brasseld committed Oct 13, 2017
1 parent 68589eb commit 1442170
Show file tree
Hide file tree
Showing 6 changed files with 400 additions and 0 deletions.
151 changes: 151 additions & 0 deletions pom.xml
@@ -0,0 +1,151 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2015 The Gravitee team (http://gravitee.io)
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>

<groupId>io.gravitee.policy</groupId>
<artifactId>gravitee-policy-openid-connect-userinfo</artifactId>
<version>1.0.0-SNAPSHOT</version>

<name>Gravitee.io APIM - Policy - OpenID Connect - UserInfo</name>
<description>Description of the OpenID Connect - UserInfo Gravitee Policy</description>

<parent>
<groupId>io.gravitee</groupId>
<artifactId>gravitee-parent</artifactId>
<version>7</version>
</parent>

<properties>
<gravitee-gateway-api.version>1.5.0</gravitee-gateway-api.version>
<gravitee-policy-api.version>1.2.0</gravitee-policy-api.version>
<gravitee-resource-api.version>1.0.0</gravitee-resource-api.version>
<gravitee-common.version>1.5.0</gravitee-common.version>
<gravitee-resource-oauth2-provider-api.version>1.1.0-SNAPSHOT</gravitee-resource-oauth2-provider-api.version>
<maven-assembly-plugin.version>2.5.5</maven-assembly-plugin.version>
<jackson.version>2.5.3</jackson.version>
</properties>

<dependencies>
<!-- Provided scope -->
<dependency>
<groupId>io.gravitee.gateway</groupId>
<artifactId>gravitee-gateway-api</artifactId>
<version>${gravitee-gateway-api.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>io.gravitee.resource</groupId>
<artifactId>gravitee-resource-api</artifactId>
<version>${gravitee-resource-api.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>io.gravitee.policy</groupId>
<artifactId>gravitee-policy-api</artifactId>
<version>${gravitee-policy-api.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>io.gravitee.common</groupId>
<artifactId>gravitee-common</artifactId>
<version>${gravitee-common.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>io.gravitee.resource</groupId>
<artifactId>gravitee-resource-oauth2-provider-api</artifactId>
<version>${gravitee-resource-oauth2-provider-api.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>

<!-- Jackson dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<scope>provided</scope>
</dependency>

<!-- Test scope -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/policy-assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-policy-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

</project>
59 changes: 59 additions & 0 deletions src/assembly/policy-assembly.xml
@@ -0,0 +1,59 @@
<!--
Copyright (C) 2015 The Gravitee team (http://gravitee.io)
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.
-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>policy</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>

<!-- Include the main Policy Jar file -->
<files>
<file>
<source>${project.build.directory}/${project.build.finalName}.jar</source>
</file>
</files>

<fileSets>
<!-- Then include Policy configuration schemas -->
<fileSet>
<directory>src/main/resources/schemas</directory>
<outputDirectory>schemas</outputDirectory>
</fileSet>

<!-- Create the empty lib directory in case of no libraries is required -->
<!-- As there is no maven-assembly-plugin's method do to that, we hack it ourself -->
<fileSet>
<directory>${project.basedir}/src/assembly</directory>
<outputDirectory>lib</outputDirectory>
<excludes>
<exclude>*</exclude>
</excludes>
</fileSet>
</fileSets>

<!-- Finally include Policy dependencies -->
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
</dependencySet>
</dependencySets>
</assembly>
119 changes: 119 additions & 0 deletions src/main/java/io/gravitee/policy/openid/userinfo/UserInfoPolicy.java
@@ -0,0 +1,119 @@
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.
*/
package io.gravitee.policy.openid.userinfo;

import io.gravitee.common.http.HttpHeaders;
import io.gravitee.common.http.HttpStatusCode;
import io.gravitee.common.http.MediaType;
import io.gravitee.gateway.api.ExecutionContext;
import io.gravitee.gateway.api.Request;
import io.gravitee.gateway.api.Response;
import io.gravitee.gateway.api.handler.Handler;
import io.gravitee.policy.api.PolicyChain;
import io.gravitee.policy.api.PolicyResult;
import io.gravitee.policy.api.annotations.OnRequest;
import io.gravitee.policy.openid.userinfo.configuration.UserInfoPolicyConfiguration;
import io.gravitee.resource.api.ResourceManager;
import io.gravitee.resource.oauth2.api.OAuth2Resource;
import io.gravitee.resource.oauth2.api.openid.UserInfoResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public class UserInfoPolicy {

private final static Logger logger = LoggerFactory.getLogger(UserInfoPolicy.class);

private static final String BEARER_TYPE = "Bearer";

static final String CONTEXT_ATTRIBUTE_OAUTH_ACCESS_TOKEN = "oauth.access_token";
static final String CONTEXT_ATTRIBUTE_OPENID_USERINFO_PAYLOAD = "openid.userinfo.payload";
private UserInfoPolicyConfiguration userInfoPolicyConfiguration;

public UserInfoPolicy (UserInfoPolicyConfiguration userInfoPolicyConfiguration) {
this.userInfoPolicyConfiguration = userInfoPolicyConfiguration;
}

@OnRequest
public void onRequest(Request request, Response response, ExecutionContext executionContext, PolicyChain policyChain) {
logger.debug("Read access_token from request {}", request.id());

OAuth2Resource oauth2 = executionContext.getComponent(ResourceManager.class).getResource(
userInfoPolicyConfiguration.getOauthResource(), OAuth2Resource.class);

if (oauth2 == null) {
policyChain.failWith(PolicyResult.failure(HttpStatusCode.UNAUTHORIZED_401,
"No OpenID Connect authorization server has been configured"));
return;
}

if (request.headers() == null || request.headers().get(HttpHeaders.AUTHORIZATION) == null || request.headers().get(HttpHeaders.AUTHORIZATION).isEmpty()) {
response.headers().add(HttpHeaders.WWW_AUTHENTICATE, BEARER_TYPE+" realm=gravitee.io - No OAuth authorization header was supplied");
policyChain.failWith(PolicyResult.failure(HttpStatusCode.UNAUTHORIZED_401,
"No OAuth authorization header was supplied"));
return;
}

Optional<String> optionalHeaderAccessToken = request.headers().get(HttpHeaders.AUTHORIZATION).stream().filter(h -> h.startsWith("Bearer")).findFirst();
if (!optionalHeaderAccessToken.isPresent()) {
response.headers().add(HttpHeaders.WWW_AUTHENTICATE, BEARER_TYPE+" realm=gravitee.io - No OAuth authorization header was supplied");
policyChain.failWith(PolicyResult.failure(HttpStatusCode.UNAUTHORIZED_401,
"No OAuth authorization header was supplied"));
return;
}

String accessToken = optionalHeaderAccessToken.get().substring(BEARER_TYPE.length()).trim();
if (accessToken.isEmpty()) {
response.headers().add(HttpHeaders.WWW_AUTHENTICATE, BEARER_TYPE+" realm=gravitee.io - No OAuth access token was supplied");
policyChain.failWith(PolicyResult.failure(HttpStatusCode.UNAUTHORIZED_401,
"No OAuth access token was supplied"));
return;
}

// Set access_token in context
executionContext.setAttribute(CONTEXT_ATTRIBUTE_OAUTH_ACCESS_TOKEN, accessToken);

// Validate access token
oauth2.userInfo(accessToken, handleResponse(policyChain, request, response, executionContext));
}

private Handler<UserInfoResponse> handleResponse(PolicyChain policyChain, Request request, Response response, ExecutionContext executionContext) {
return userInfoResponse -> {
if (userInfoResponse.isSuccess()) {
if (userInfoPolicyConfiguration.isExtractPayload()) {
executionContext.setAttribute(CONTEXT_ATTRIBUTE_OPENID_USERINFO_PAYLOAD, userInfoResponse.getPayload());
}

policyChain.doNext(request, response);
} else {
response.headers().add(HttpHeaders.WWW_AUTHENTICATE, BEARER_TYPE+" realm=gravitee.io " + userInfoResponse.getPayload());

if (userInfoResponse.getThrowable() == null) {
policyChain.failWith(PolicyResult.failure(HttpStatusCode.UNAUTHORIZED_401,
userInfoResponse.getPayload(), MediaType.APPLICATION_JSON));
} else {
policyChain.failWith(PolicyResult.failure(HttpStatusCode.SERVICE_UNAVAILABLE_503,
"Service Unavailable"));
}
}
};
}
}
@@ -0,0 +1,45 @@
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.
*/
package io.gravitee.policy.openid.userinfo.configuration;

import io.gravitee.policy.api.PolicyConfiguration;

/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public class UserInfoPolicyConfiguration implements PolicyConfiguration {

private String oauthResource;

private boolean extractPayload = false;

public String getOauthResource() {
return oauthResource;
}

public void setOauthResource(String oauthResource) {
this.oauthResource = oauthResource;
}

public boolean isExtractPayload() {
return extractPayload;
}

public void setExtractPayload(boolean extractPayload) {
this.extractPayload = extractPayload;
}
}
6 changes: 6 additions & 0 deletions src/main/resources/plugin.properties
@@ -0,0 +1,6 @@
id=policy-openid-userinfo
name=OpenID Connect - UserInfo
version=${project.version}
description=${project.description}
class=io.gravitee.policy.openid.userinfo.UserInfoPolicy
type=policy

0 comments on commit 1442170

Please sign in to comment.