com.databricks.sdk.core.oauth.ClientCredentials Maven / Gradle / Ivy
package com.databricks.sdk.core.oauth;
import com.databricks.sdk.core.commons.CommonsHttpClient;
import com.databricks.sdk.core.http.HttpClient;
import java.util.*;
/**
* An implementation of RefreshableTokenSource implementing the client_credentials OAuth grant type.
*
* Using the provided client ID, secret, and token URL, this class makes requests using its
* HttpClient to fetch OAuth tokens. Additional parameters and scopes can be specified as well. To
* support all OAuth endpoints, authentication parameters can be passed in the request body or in
* the Authorization header.
*/
public class ClientCredentials extends RefreshableTokenSource {
public static class Builder {
private String clientId;
private String clientSecret;
private String tokenUrl;
private HttpClient hc = new CommonsHttpClient.Builder().withTimeoutSeconds(30).build();
private Map endpointParams = Collections.emptyMap();
private List scopes = Collections.emptyList();
private AuthParameterPosition position = AuthParameterPosition.BODY;
public Builder withClientId(String clientId) {
this.clientId = clientId;
return this;
}
public Builder withClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
public Builder withTokenUrl(String tokenUrl) {
this.tokenUrl = tokenUrl;
return this;
}
public Builder withEndpointParameters(Map params) {
this.endpointParams = params;
return this;
}
public Builder withScopes(List scopes) {
this.scopes = scopes;
return this;
}
public Builder withAuthParameterPosition(AuthParameterPosition position) {
this.position = position;
return this;
}
public Builder withHttpClient(HttpClient hc) {
this.hc = hc;
return this;
}
public ClientCredentials build() {
Objects.requireNonNull(this.clientId, "clientId must be specified");
Objects.requireNonNull(this.clientSecret, "clientSecret must be specified");
Objects.requireNonNull(this.tokenUrl, "tokenUrl must be specified");
return new ClientCredentials(
hc, clientId, clientSecret, tokenUrl, endpointParams, scopes, position);
}
}
private HttpClient hc;
private String clientId;
private String clientSecret;
private String tokenUrl;
private Map endpointParams;
private List scopes;
private AuthParameterPosition position;
private ClientCredentials(
HttpClient hc,
String clientId,
String clientSecret,
String tokenUrl,
Map endpointParams,
List scopes,
AuthParameterPosition position) {
this.hc = hc;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.tokenUrl = tokenUrl;
this.endpointParams = endpointParams;
this.scopes = scopes;
this.position = position;
}
@Override
protected Token refresh() {
Map params = new HashMap<>();
params.put("grant_type", "client_credentials");
if (scopes != null) {
params.put("scope", String.join(" ", scopes));
}
if (endpointParams != null) {
params.putAll(endpointParams);
}
return retrieveToken(hc, clientId, clientSecret, tokenUrl, params, new HashMap<>(), position);
}
}