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

[oauth] User-defined scope in AccessTokenResponse #1891

Merged
merged 10 commits into from
Dec 23, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonDeserializer;

/**
* Implementation of OAuthClientService.
*
Expand Down Expand Up @@ -150,7 +152,7 @@ public String getAuthorizationUrl(@Nullable String redirectURI, @Nullable String
throw new OAuthException("Missing client ID");
}

OAuthConnector connector = new OAuthConnector(httpClientFactory);
OAuthConnector connector = new OAuthConnector(httpClientFactory, persistedParams.deserializerClassName);
clinique marked this conversation as resolved.
Show resolved Hide resolved
return connector.getAuthorizationUrl(authorizationUrl, clientId, redirectURI, persistedParams.state,
scopeToUse);
}
Expand Down Expand Up @@ -204,7 +206,7 @@ public AccessTokenResponse getAccessTokenResponseByAuthorizationCode(String auth
throw new OAuthException("Missing client ID");
}

OAuthConnector connector = new OAuthConnector(httpClientFactory);
OAuthConnector connector = new OAuthConnector(httpClientFactory, persistedParams.deserializerClassName);
AccessTokenResponse accessTokenResponse = connector.grantTypeAuthorizationCode(tokenUrl, authorizationCode,
clientId, persistedParams.clientSecret, redirectURI,
Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
Expand Down Expand Up @@ -236,7 +238,7 @@ public AccessTokenResponse getAccessTokenByResourceOwnerPasswordCredentials(Stri
throw new OAuthException("Missing token url");
}

OAuthConnector connector = new OAuthConnector(httpClientFactory);
OAuthConnector connector = new OAuthConnector(httpClientFactory, persistedParams.deserializerClassName);
AccessTokenResponse accessTokenResponse = connector.grantTypePassword(tokenUrl, username, password,
persistedParams.clientId, persistedParams.clientSecret, scope,
Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
Expand All @@ -261,7 +263,7 @@ public AccessTokenResponse getAccessTokenByClientCredentials(@Nullable String sc
throw new OAuthException("Missing client ID");
}

OAuthConnector connector = new OAuthConnector(httpClientFactory);
OAuthConnector connector = new OAuthConnector(httpClientFactory, persistedParams.deserializerClassName);
// depending on usage, cannot guarantee every parameter is not null at the beginning
AccessTokenResponse accessTokenResponse = connector.grantTypeClientCredentials(tokenUrl, clientId,
persistedParams.clientSecret, scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
Expand Down Expand Up @@ -295,7 +297,7 @@ public AccessTokenResponse refreshToken() throws OAuthException, IOException, OA
throw new OAuthException("tokenUrl is required but null");
}

OAuthConnector connector = new OAuthConnector(httpClientFactory);
OAuthConnector connector = new OAuthConnector(httpClientFactory, persistedParams.deserializerClassName);
AccessTokenResponse accessTokenResponse = connector.grantTypeRefreshToken(tokenUrl,
lastAccessToken.getRefreshToken(), persistedParams.clientId, persistedParams.clientSecret,
persistedParams.scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
Expand Down Expand Up @@ -395,4 +397,17 @@ public boolean removeAccessTokenRefreshListener(AccessTokenRefreshListener liste
private String createNewState() {
return UUID.randomUUID().toString();
}

@Override
public <T extends JsonDeserializer<?>> OAuthClientService withDeserializer(Class<T> deserializerClass) {
OAuthClientServiceImpl clientService = new OAuthClientServiceImpl(handle, persistedParams.tokenExpiresInSeconds,
clinique marked this conversation as resolved.
Show resolved Hide resolved
httpClientFactory);
persistedParams.deserializerClassName = deserializerClass.getName();
clientService.persistedParams = persistedParams;
clientService.storeHandler = storeHandler;

storeHandler.savePersistedParams(handle, clientService.persistedParams);

return clientService;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import static org.openhab.core.auth.oauth2client.internal.Keyword.*;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
Expand Down Expand Up @@ -65,9 +66,21 @@ public class OAuthConnector {
private final Logger logger = LoggerFactory.getLogger(OAuthConnector.class);
private final Gson gson;

public OAuthConnector(HttpClientFactory httpClientFactory) {
public OAuthConnector(HttpClientFactory httpClientFactory, @Nullable String deserializerClassName) {
this.httpClientFactory = httpClientFactory;
gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
GsonBuilder gsonBuilder = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
if (deserializerClassName != null) {
try {
Class<?> deserializerClass = Class.forName(deserializerClassName);
gsonBuilder = gsonBuilder.registerTypeAdapter(AccessTokenResponse.class,
deserializerClass.getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException
| ClassNotFoundException e) {
logger.error("Unable to construct custom deserializer '{}'", deserializerClassName, e);
}
}
gson = gsonBuilder.create();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public OAuthClientService createOAuthClientService(String handle, String tokenUr
@Nullable Boolean supportsBasicAuth) {
PersistedParams params = oAuthStoreHandler.loadPersistedParams(handle);
PersistedParams newParams = new PersistedParams(handle, tokenUrl, authorizationUrl, clientId, clientSecret,
scope, supportsBasicAuth, tokenExpiresInBuffer);
scope, supportsBasicAuth, tokenExpiresInBuffer, null);
OAuthClientService clientImpl = null;

// If parameters in storage and parameters are the same as arguments passed get the client from storage
Expand Down Expand Up @@ -138,4 +138,5 @@ public int getTokenExpiresInBuffer() {
public void setTokenExpiresInBuffer(int bufferInSeconds) {
tokenExpiresInBuffer = bufferInSeconds;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class PersistedParams {
String state;
String redirectUri;
int tokenExpiresInSeconds = 60;
String deserializerClassName;
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
String deserializerClassName;
@Nullable String deserializerClassName;


/**
* Default constructor needed for json serialization.
Expand All @@ -56,9 +57,11 @@ public PersistedParams() {
* of the access tokens. This allows the access token to expire earlier than the
* official stated expiry time; thus prevents the caller obtaining a valid token at the time of invoke,
* only to find the token immediately expired.
* @param deserializerClass
*/
public PersistedParams(String handle, String tokenUrl, String authorizationUrl, String clientId,
String clientSecret, String scope, Boolean supportsBasicAuth, int tokenExpiresInSeconds) {
String clientSecret, String scope, Boolean supportsBasicAuth, int tokenExpiresInSeconds,
@Nullable String deserializerClassName) {
this.handle = handle;
this.tokenUrl = tokenUrl;
this.authorizationUrl = authorizationUrl;
Expand All @@ -67,6 +70,7 @@ public PersistedParams(String handle, String tokenUrl, String authorizationUrl,
this.scope = scope;
this.supportsBasicAuth = supportsBasicAuth;
this.tokenExpiresInSeconds = tokenExpiresInSeconds;
this.deserializerClassName = deserializerClassName;
}

@Override
Expand All @@ -83,6 +87,7 @@ public int hashCode() {
result = prime * result + ((supportsBasicAuth == null) ? 0 : supportsBasicAuth.hashCode());
result = prime * result + tokenExpiresInSeconds;
result = prime * result + ((tokenUrl == null) ? 0 : tokenUrl.hashCode());
result = prime * result + ((deserializerClassName == null) ? 0 : deserializerClassName.hashCode());
return result;
}

Expand Down Expand Up @@ -161,6 +166,14 @@ public boolean equals(@Nullable Object obj) {
} else if (!tokenUrl.equals(other.tokenUrl)) {
return false;
}
if (deserializerClassName == null) {
if (other.deserializerClassName != null) {
return false;
}
} else if (!deserializerClassName.equals(other.deserializerClassName)) {
return false;
}

return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;

import com.google.gson.JsonDeserializer;

/**
* This is the service factory to produce a OAuth2 service client that authenticates using OAUTH2.
* This is a service factory pattern; the OAuthe2 service client is not shared between bundles.
Expand Down Expand Up @@ -286,4 +288,13 @@ AccessTokenResponse getAccessTokenByImplicit(@Nullable String redirectURI, @Null
* @param listener the listener to remove
*/
boolean removeAccessTokenRefreshListener(AccessTokenRefreshListener listener);

/**
* Adds a personalized deserializer to a given oauth service.
*
* @param deserializeClass the deserializer class that should be used to deserialize AccessTokenResponse
* @return the oauth service
*/
<T extends JsonDeserializer<?>> OAuthClientService withDeserializer(Class<T> deserializerClass);

}