Skip to content
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
2 changes: 1 addition & 1 deletion authentication-lib-main/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<parent>
<groupId>com.sphereon.public</groupId>
<artifactId>authentication-lib-modules</artifactId>
<version>0.1.8-SNAPSHOT</version>
<version>0.2.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public interface TokenRequestBuilder {

TokenRequest build();


final class Builder {

private final ApiConfiguration configuration;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ public interface ApiConfiguration extends ApiConfigurator {

void setGatewayBaseUrl(String gatewayBaseUrl);

String getTokenEndpointPath();

void setTokenEndpointPath(String tokenEndpointPath);

PersistenceType getPersistenceType();

void setPersistenceType(PersistenceType persistenceType);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2017 Sphereon BV https://sphereon.com
*
* 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 com.sphereon.libs.authentication.api.config;

import com.sphereon.commons.exceptions.EnumParseException;
import org.apache.commons.lang3.StringUtils;

public enum ClientCredentialsMode {
BASIC_HEADER, BODY;


public static ClientCredentialsMode fromString(String value) {
if (StringUtils.isNotEmpty(value)) {
for (ClientCredentialsMode persistenceMode : ClientCredentialsMode.values()) {
if (reformat(persistenceMode.name()).equals(reformat(value))) {
return persistenceMode;
}
}
}
throw new EnumParseException("Could not parse " + value + " as ClientCredentialsMode");
}


private static String reformat(String value) {
return value.replace("_", "")
.replace("-", "")
.toLowerCase();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class ApiConfigurationImpl implements ApiConfiguration, ConfigPersistence, Confi
private PersistenceMode persistenceMode = PersistenceMode.READ_ONLY;

private String gatewayBaseUrl = DEFAULT_GATEWAY_URL;
private String tokenEndpointPath;

private File standalonePropertyFile;

Expand Down Expand Up @@ -87,6 +88,15 @@ public void setGatewayBaseUrl(String gatewayBaseUrl) {
this.gatewayBaseUrl = gatewayBaseUrl;
}

@Override
public String getTokenEndpointPath() {
return tokenEndpointPath;
}

@Override
public void setTokenEndpointPath(final String tokenEndpointPath) {
this.tokenEndpointPath = tokenEndpointPath;
}

@Override
public PersistenceType getPersistenceType() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ public Builder withGatewayBaseUrl(String gatewayBaseUrl) {
return this;
}

public Builder withTokenEndpointPath(String path) {
configuration.setTokenEndpointPath(path);
return this;
}


public ApiConfiguration build() {
validate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.sphereon.libs.authentication.api.TokenRequest;
import com.sphereon.libs.authentication.api.TokenRequestBuilder;
import com.sphereon.libs.authentication.api.config.ApiConfiguration;
import com.sphereon.libs.authentication.api.config.ClientCredentialsMode;
import com.sphereon.libs.authentication.api.granttypes.Grant;
import com.sphereon.libs.authentication.impl.config.ConfigManager;
import com.sphereon.libs.authentication.impl.config.ConfigManagerProvider;
Expand All @@ -37,14 +38,21 @@ class Builder implements TokenRequestBuilder {
private String consumerSecret;
private Grant grant;
private String scope;
private String resource;
private Long validityPeriodInSeconds;
private ClientCredentialsMode clientCredentialsMode;


public Builder(ApiConfiguration configuration) {
this.configuration = configuration;
}


public GenerateTokenRequestBuilder.Builder withClientCredentialsMode(final ClientCredentialsMode clientCredentialsMode) {
this.clientCredentialsMode = clientCredentialsMode;
return this;
}

public GenerateTokenRequestBuilder.Builder withConsumerKey(String consumerKey) {
this.consumerKey = consumerKey;
return this;
Expand All @@ -68,6 +76,11 @@ public GenerateTokenRequestBuilder.Builder withScope(String scope) {
return this;
}

public GenerateTokenRequestBuilder.Builder withResource(String resource) {
this.resource = resource;
return this;
}


public GenerateTokenRequestBuilder.Builder withValidityPeriod(int validityPeriodInSeconds) {
this.validityPeriodInSeconds = Long.valueOf(validityPeriodInSeconds);
Expand All @@ -90,37 +103,48 @@ public TokenRequest build() {
configPersistence.loadConfig(configManager);
GenerateTokenRequestImpl tokenRequest = new GenerateTokenRequestImpl(configuration);
tokenRequest.setGrant(grant);
tokenRequest.setClientCredentialsMode(clientCredentialsMode);
tokenRequest.setConsumerKey(consumerKey);
tokenRequest.setConsumerSecret(consumerSecret);
tokenRequest.setScope(scope);
tokenRequest.setResource(resource);
tokenRequest.setValidityPeriodInSeconds(validityPeriodInSeconds);
return tokenRequest;
}


private void validate() {
if (this.grant == null) {
this.grant = configuration.getDefaultGrant();
}
if (this.grant == null) {
this.grant = new ClientCredentialBuilder.ClientCredentialGrantBuilder().build();
if (clientCredentialsMode == null) {
this.clientCredentialsMode = ClientCredentialsMode.BASIC_HEADER; // Backwards compatibility
}

if (StringUtils.isEmpty(consumerKey)) {
this.consumerKey = configuration.getConsumerKey();
}
if (StringUtils.isEmpty(consumerKey)) {
throw new IllegalArgumentException(String.format(
"The consumer key variable was not found for application %s. Please check your configuration.",
configuration.getApplication()));
if (clientCredentialsMode == ClientCredentialsMode.BASIC_HEADER) {
if (StringUtils.isEmpty(consumerKey)) {
this.consumerKey = configuration.getConsumerKey();
}
if (StringUtils.isEmpty(consumerKey)) {
throw new IllegalArgumentException(String.format(
"The consumer key variable was not found for application %s. Please check your configuration.",
configuration.getApplication()));
}
if (StringUtils.isEmpty(consumerSecret)) {
this.consumerSecret = configuration.getConsumerSecret();
}
if (StringUtils.isEmpty(consumerSecret)) {
throw new IllegalArgumentException(String.format(
"The consumer secret variable was not found for application %s. Please check your configuration.",
configuration.getApplication()));
}
}
if (StringUtils.isEmpty(consumerSecret)) {
this.consumerSecret = configuration.getConsumerSecret();
if (this.grant == null) {
this.grant = configuration.getDefaultGrant();
}
if (StringUtils.isEmpty(consumerSecret)) {
throw new IllegalArgumentException(String.format(
"The consumer secret variable was not found for application %s. Please check your configuration.",
configuration.getApplication()));
if (this.grant == null) {
this.grant = new ClientCredentialBuilder.ClientCredentialGrantBuilder()
.withClientCredentialsMode(clientCredentialsMode)
.withConsumerKey(consumerKey)
.withConsumerSecret(consumerSecret)
.build();
}
if (StringUtils.isEmpty(scope)) {
this.scope = configuration.getDefaultScope();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ private void buildAndExecuteRequestAsync() {
private Request buildRequest(HttpRequestHandler requestHandler) {
FormBody requestBody = requestHandler.buildBody(this);
Headers headers = requestHandler.buildHeaders(this);
return requestHandler.newTokenRequest(configuration.getGatewayBaseUrl(), headers, requestBody);
return requestHandler.newTokenRequest(configuration.getGatewayBaseUrl(), configuration.getTokenEndpointPath(), headers, requestBody);
}


Expand All @@ -161,37 +161,10 @@ public void bodyParameters(Map<RequestParameterKey, String> parameterMap) {
if (getScope() != null) {
parameterMap.put(RequestParameterKey.SCOPE, "" + getScope());
}
if (getResource() != null) {
parameterMap.put(RequestParameterKey.RESOURCE, "" + getResource());
}
RequestParameters grantParameters = (RequestParameters) getGrant();
grantParameters.bodyParameters(parameterMap);
}


@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof GenerateTokenRequestImpl)) {
return false;
}
if (!super.equals(o)) {
return false;
}

GenerateTokenRequestImpl that = (GenerateTokenRequestImpl) o;

if (getGrant() != null ? !getGrant().equals(that.getGrant()) : that.getGrant() != null) {
return false;
}
return getValidityPeriodInSeconds() != null ? getValidityPeriodInSeconds().equals(that.getValidityPeriodInSeconds()) : that.getValidityPeriodInSeconds() == null;
}


@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (getGrant() != null ? getGrant().hashCode() : 0);
result = 31 * result + (getValidityPeriodInSeconds() != null ? getValidityPeriodInSeconds().hashCode() : 0);
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.sphereon.libs.authentication.api.config.ApiConfiguration;
import com.sphereon.libs.authentication.impl.RequestParameters;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.Type;
Expand All @@ -44,22 +45,36 @@ public HttpRequestHandler(ApiConfiguration configuration) {
}


public Request newTokenRequest(String urlBase, Headers headers, FormBody requestBody) {
public Request newTokenRequest(String urlBase, final String tokenEndpointPath, Headers headers, FormBody requestBody) {
Assert.notNull(urlBase, "No urlBase was specified");

final StringBuilder urlBuilder = new StringBuilder(urlBase);
if (!urlBase.endsWith("/")) {
urlBuilder.append('/');
}
if (StringUtils.isNotBlank(tokenEndpointPath)) {
if (tokenEndpointPath.startsWith("/")) {
urlBuilder.append(tokenEndpointPath.substring(1));
} else {
urlBuilder.append(tokenEndpointPath);
}
} else {
urlBuilder.append(TokenPathParameters.TOKEN.getValue());
}

Request.Builder request = new Request.Builder()
.url(urlBase + TokenPathParameters.TOKEN)
.headers(headers)
.post(requestBody);
.url(urlBuilder.toString())
.headers(headers)
.post(requestBody);
return request.build();
}


public Request newRevokeRequest(String urlBase, Headers headers, FormBody requestBody) {
Request.Builder request = new Request.Builder()
.url(urlBase + TokenPathParameters.REVOKE)
.headers(headers)
.post(requestBody);
.url(StringUtils.appendIfMissing(urlBase, "/") + TokenPathParameters.REVOKE)
.headers(headers)
.post(requestBody);
return request.build();
}

Expand All @@ -84,10 +99,10 @@ public Headers buildHeaders(RequestParameters requestParameters) {
requestParameters.headerParameters(parameterMap);

Headers.Builder headerBuilder = new Headers.Builder();
headerBuilder.add("Content-Type", "application/x-www-form-urlencoded");
for (Map.Entry<RequestParameterKey, String> entry : parameterMap.entrySet()) {
Assert.notNull(entry.getValue(), "Header parameter " + entry.getKey() + " not set.");
headerBuilder.add(entry.getKey().getValue(), entry.getValue());

}
return headerBuilder.build();
}
Expand All @@ -106,8 +121,8 @@ public String getResponseBodyContent(Response response) throws IOException {
Assert.notNull(responseBody, "The remote endpoint did not return a response body.");
String responseBodyString = responseBody.string();
Assert.isTrue(!"application/json".equals(responseBody.contentType()),
String.format("The remote endpoint responded with content type %s while application/json is expected. Content:%n%s",
responseBody.contentType(), responseBodyString));
String.format("The remote endpoint responded with content type %s while application/json is expected. Content:%n%s",
responseBody.contentType(), responseBodyString));
return responseBodyString;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@ public enum RequestParameterKey implements StringValueEnum {
GRANT_TYPE("grant_type"),
USER_NAME("username"),
PASSWORD("password"),

CLIENT_ID("client_id"),
CLIENT_SECRET("client_secret"),
REFRESH_TOKEN("refresh_token"),
WINDOWS_TOKEN("windows_token"),
KERBEROS_REALM("kerberos_realm"),
KERBEROS_TOKEN("kerberos_token"),
ASSERTION("assertions"),
VALIDITY_PERIOD("validity_period"),
SCOPE("scope"),
RESOURCE("resource"),
AUTHORIZATION("Authorization"),
TOKEN("token");

Expand Down
Loading