Skip to content
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

Moved the code from Spring Cloud Security #445

Merged
merged 1 commit into from
Dec 16, 2020
Merged
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
5 changes: 5 additions & 0 deletions spring-cloud-openfeign-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@
<artifactId>okhttp</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was hoping to move to the new stuff, but just having this moved is better. I think there's an open issue, that can come in a SR

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this one that should be moved to this project probably spring-attic/spring-cloud-security#173
in the comments there are links to a couple of possible implementation using Spring Security only

<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

import feign.Client;
import feign.Feign;
import feign.RequestInterceptor;
import feign.httpclient.ApacheHttpClient;
import feign.okhttp.OkHttpClient;
import okhttp3.ConnectionPool;
Expand All @@ -39,6 +40,7 @@
import org.apache.http.impl.client.CloseableHttpClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
Expand All @@ -48,11 +50,14 @@
import org.springframework.cloud.commons.httpclient.ApacheHttpClientFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientConnectionPoolFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.security.OAuth2FeignRequestInterceptor;
import org.springframework.cloud.openfeign.support.DefaultGzipDecoderConfiguration;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;

/**
* @author Spencer Gibb
Expand Down Expand Up @@ -209,4 +214,19 @@ public Client feignClient(okhttp3.OkHttpClient client) {

}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OAuth2ClientContext.class)
@ConditionalOnProperty("feign.oauth2.enabled")
protected static class Oauth2FeignConfiguration {

@Bean
@ConditionalOnMissingBean(OAuth2FeignRequestInterceptor.class)
@ConditionalOnBean({ OAuth2ClientContext.class, OAuth2ProtectedResourceDetails.class })
public RequestInterceptor oauth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) {
return new OAuth2FeignRequestInterceptor(oAuth2ClientContext, resource);
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/*
* Copyright 2015-2019 the original author or authors.
*
* 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
*
* https://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 org.springframework.cloud.openfeign.security;

import java.util.Arrays;

import feign.RequestInterceptor;
import feign.RequestTemplate;

import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenProviderChain;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

/**
* Pre-defined custom RequestInterceptor for Feign Requests. It uses the
* {@link OAuth2ClientContext OAuth2ClientContext} provided from the environment and
* construct a new header on the request before it is made by Feign.
*
* @author Joao Pedro Evangelista
* @author Tim Ysewyn
* @since 3.0.0
*/
public class OAuth2FeignRequestInterceptor implements RequestInterceptor {

/**
* The name of the token.
*/
public static final String BEARER = "Bearer";

/**
* The name of the header.
*/
public static final String AUTHORIZATION = "Authorization";

private final OAuth2ClientContext oAuth2ClientContext;

private final OAuth2ProtectedResourceDetails resource;

private final String tokenType;

private final String header;

private AccessTokenProvider accessTokenProvider = new AccessTokenProviderChain(Arrays.<AccessTokenProvider>asList(
new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(),
new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider()));

/**
* Default constructor which uses the provided OAuth2ClientContext and Bearer tokens
* within Authorization header.
* @param oAuth2ClientContext provided context
* @param resource type of resource to be accessed
*/
public OAuth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource) {
this(oAuth2ClientContext, resource, BEARER, AUTHORIZATION);
}

/**
* Fully customizable constructor for changing token type and header name, in cases of
* Bearer and Authorization is not the default such as "bearer", "authorization".
* @param oAuth2ClientContext current oAuth2 Context
* @param resource type of resource to be accessed
* @param tokenType type of token e.g. "token", "Bearer"
* @param header name of the header e.g. "Authorization", "authorization"
*/
public OAuth2FeignRequestInterceptor(OAuth2ClientContext oAuth2ClientContext,
OAuth2ProtectedResourceDetails resource, String tokenType, String header) {
this.oAuth2ClientContext = oAuth2ClientContext;
this.resource = resource;
this.tokenType = tokenType;
this.header = header;
}

/**
* Create a template with the header of provided name and extracted extract.
*
* @see RequestInterceptor#apply(RequestTemplate)
*/
@Override
public void apply(RequestTemplate template) {
template.header(header); // Clears out the header, no "clear" method available.
template.header(header, extract(tokenType));
}

/**
* Extracts the token extract id the access token exists or returning an empty extract
* if there is no one on the context it may occasionally causes Unauthorized response
* since the token extract is empty.
* @param tokenType type name of token
* @return token value from context if it exists otherwise empty String
*/
protected String extract(String tokenType) {
OAuth2AccessToken accessToken = getToken();
return String.format("%s %s", tokenType, accessToken.getValue());
}

/**
* Extract the access token within the request or try to acquire a new one by
* delegating it to {@link #acquireAccessToken()}.
* @return valid token
*/
public OAuth2AccessToken getToken() {

OAuth2AccessToken accessToken = oAuth2ClientContext.getAccessToken();
if (accessToken == null || accessToken.isExpired()) {
try {
accessToken = acquireAccessToken();
}
catch (UserRedirectRequiredException e) {
oAuth2ClientContext.setAccessToken(null);
String stateKey = e.getStateKey();
if (stateKey != null) {
Object stateToPreserve = e.getStateToPreserve();
if (stateToPreserve == null) {
stateToPreserve = "NONE";
}
oAuth2ClientContext.setPreservedState(stateKey, stateToPreserve);
}
throw e;
}
}
return accessToken;
}

/**
* Try to acquire the token using a access token provider.
* @return valid access token
* @throws UserRedirectRequiredException in case the user needs to be redirected to an
* approval page or login page
*/
protected OAuth2AccessToken acquireAccessToken() throws UserRedirectRequiredException {
AccessTokenRequest tokenRequest = oAuth2ClientContext.getAccessTokenRequest();
if (tokenRequest == null) {
throw new AccessTokenRequiredException(
"Cannot find valid context on request for resource '" + resource.getId() + "'.", resource);
}
String stateKey = tokenRequest.getStateKey();
if (stateKey != null) {
tokenRequest.setPreservedState(oAuth2ClientContext.removePreservedState(stateKey));
}
OAuth2AccessToken existingToken = oAuth2ClientContext.getAccessToken();
if (existingToken != null) {
oAuth2ClientContext.setAccessToken(existingToken);
}
OAuth2AccessToken obtainableAccessToken;
obtainableAccessToken = accessTokenProvider.obtainAccessToken(resource, tokenRequest);
if (obtainableAccessToken == null || obtainableAccessToken.getValue() == null) {
throw new IllegalStateException(
" Access token provider returned a null token, which is illegal according to the contract.");
}
oAuth2ClientContext.setAccessToken(obtainableAccessToken);
return obtainableAccessToken;
}

public void setAccessTokenProvider(AccessTokenProvider accessTokenProvider) {
this.accessTokenProvider = accessTokenProvider;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2015-2015 the original author or authors.
*
* 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
*
* https://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 org.springframework.cloud.openfeign.security;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.resource.UserApprovalRequiredException;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.oauth2.client.token.AccessTokenProvider;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;

/**
* Mocks the access token provider
*
* @author Mihhail Verhovtsov
*/
public class MockAccessTokenProvider implements AccessTokenProvider {

private OAuth2AccessToken token;

public MockAccessTokenProvider(OAuth2AccessToken token) {
this.token = token;
}

@Override
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
AccessTokenRequest accessTokenRequest)
throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException {
return token;
}

@Override
public boolean supportsResource(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails) {
return true;
}

@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
OAuth2RefreshToken oAuth2RefreshToken, AccessTokenRequest accessTokenRequest)
throws UserRedirectRequiredException {
return null;
}

@Override
public boolean supportsRefresh(OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails) {
return false;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright 2015-2015 the original author or authors.
*
* 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
*
* https://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 org.springframework.cloud.openfeign.security;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;

/**
* Mocks the OAuth2 access token
*
* @author Mihhail Verhovtsov
*/
public class MockOAuth2AccessToken implements OAuth2AccessToken {

private String value;

public MockOAuth2AccessToken(String value) {
this.value = value;
}

@Override
public Map<String, Object> getAdditionalInformation() {
return null;
}

@Override
public Set<String> getScope() {
return null;
}

@Override
public OAuth2RefreshToken getRefreshToken() {
return null;
}

@Override
public String getTokenType() {
return null;
}

@Override
public boolean isExpired() {
return false;
}

@Override
public Date getExpiration() {
return null;
}

@Override
public int getExpiresIn() {
return 0;
}

@Override
public String getValue() {
return value;
}

}
Loading