Skip to content
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
2 changes: 1 addition & 1 deletion .codegen.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "engineHash": "0eab570", "specHash": "7f8494a", "version": "10.21.0" }
{ "engineHash": "6772894", "specHash": "7f8494a", "version": "10.21.0" }
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ dependencies {
implementation "org.bouncycastle:bcprov-jdk18on:${bouncyCastleBcprovJdk18onVersion}"
implementation "org.bouncycastle:bcpkix-jdk18on:${bouncyCastleBcpkixJdk18onVersion}"
testImplementation "org.junit.jupiter:junit-jupiter-api:${junitApiVersion}"
testImplementation "com.squareup.okhttp3:mockwebserver:${okhttpVersion}"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junitEngineVersion}"
}
spotless {
Expand Down
2 changes: 2 additions & 0 deletions docs/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ This method allows you to make any HTTP request to the Box API. It will automati
network configuration settings from the client.
The method accepts a `FetchOptions` object as an argument and returns a `FetchResponse` object.

For request bodies that cannot be safely replayed, such as a JWT assertion with a one-time `jti`, `FetchOptions` also accepts `dataFactory`. `dataFactory.create()` is called on the first attempt when `data` is not set and on each retry so each retry can send a fresh body.

## JSON request

The following example demonstrates how to make a custom POST request to create a new folder in the root folder.
Expand Down
58 changes: 24 additions & 34 deletions src/main/java/com/box/sdkgen/box/jwtauth/BoxJWTAuth.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
package com.box.sdkgen.box.jwtauth;

import static com.box.sdkgen.internal.utils.UtilsManager.createJwtAssertion;
import static com.box.sdkgen.internal.utils.UtilsManager.entryOf;
import static com.box.sdkgen.internal.utils.UtilsManager.getEpochTimeInSeconds;
import static com.box.sdkgen.internal.utils.UtilsManager.getUuid;
import static com.box.sdkgen.internal.utils.UtilsManager.isBrowser;
import static com.box.sdkgen.internal.utils.UtilsManager.mapOf;

import com.box.sdkgen.box.errors.BoxSDKError;
import com.box.sdkgen.box.tokenstorage.InMemoryTokenStorage;
import com.box.sdkgen.box.tokenstorage.TokenStorage;
import com.box.sdkgen.internal.utils.JwtKey;
import com.box.sdkgen.internal.utils.JwtSignOptions;
import com.box.sdkgen.managers.authorization.AuthorizationManager;
import com.box.sdkgen.networking.auth.Authentication;
import com.box.sdkgen.networking.fetchoptions.FetchOptions;
import com.box.sdkgen.networking.fetchoptions.ResponseFormat;
import com.box.sdkgen.networking.fetchresponse.FetchResponse;
import com.box.sdkgen.networking.network.NetworkSession;
import com.box.sdkgen.schemas.accesstoken.AccessToken;
import com.box.sdkgen.schemas.postoauth2revoke.PostOAuth2Revoke;
import com.box.sdkgen.schemas.postoauth2token.PostOAuth2Token;
import com.box.sdkgen.schemas.postoauth2token.PostOAuth2TokenGrantTypeField;
import com.box.sdkgen.schemas.postoauth2token.PostOAuth2TokenSubjectTokenTypeField;
import com.box.sdkgen.serialization.json.JsonManager;
import java.util.List;
import java.util.Map;

public class BoxJWTAuth implements Authentication {

Expand Down Expand Up @@ -68,33 +64,27 @@ public AccessToken refreshToken(NetworkSession networkSession) {
if (isBrowser()) {
throw new BoxSDKError("JWT auth is not supported in browser environment.");
}
Map<String, Object> claims =
mapOf(
entryOf("exp", getEpochTimeInSeconds() + 30),
entryOf("box_sub_type", this.subjectType));
JwtSignOptions jwtOptions =
new JwtSignOptions(
this.config.getAlgorithm(),
"https://api.box.com/oauth2/token",
this.config.getClientId(),
this.subjectId,
getUuid(),
this.config.getJwtKeyId(),
this.config.getPrivateKeyDecryptor());
JwtKey jwtKey = new JwtKey(this.config.getPrivateKey(), this.config.getPrivateKeyPassphrase());
String assertion = createJwtAssertion(claims, jwtKey, jwtOptions);
AuthorizationManager authManager =
new AuthorizationManager.Builder()
.networkSession((!(networkSession == null) ? networkSession : new NetworkSession()))
NetworkSession networkSessionToUse =
(!(networkSession == null) ? networkSession : new NetworkSession());
JwtAccessTokenDataFactory dataFactory =
new JwtAccessTokenDataFactory.Builder(this.config)
.subjectId(this.subjectId)
.subjectType(this.subjectType)
.build();
AccessToken token =
authManager.requestAccessToken(
new PostOAuth2Token.Builder(
PostOAuth2TokenGrantTypeField.URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER)
.assertion(assertion)
.clientId(this.config.getClientId())
.clientSecret(this.config.getClientSecret())
.build());
FetchResponse response =
networkSessionToUse
.getNetworkClient()
.fetch(
new FetchOptions.Builder(
String.join(
"", networkSessionToUse.getBaseUrls().getBaseUrl(), "/oauth2/token"),
"POST")
.dataFactory(dataFactory)
.contentType("application/x-www-form-urlencoded")
.responseFormat(ResponseFormat.JSON)
.networkSession(networkSessionToUse)
.build());
AccessToken token = JsonManager.deserialize(response.getData(), AccessToken.class);
this.tokenStorage.store(token);
return token;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.box.sdkgen.box.jwtauth;

import static com.box.sdkgen.internal.utils.UtilsManager.createJwtAssertion;
import static com.box.sdkgen.internal.utils.UtilsManager.entryOf;
import static com.box.sdkgen.internal.utils.UtilsManager.getEpochTimeInSeconds;
import static com.box.sdkgen.internal.utils.UtilsManager.getUuid;
import static com.box.sdkgen.internal.utils.UtilsManager.mapOf;

import com.box.sdkgen.internal.utils.JwtKey;
import com.box.sdkgen.internal.utils.JwtSignOptions;
import com.box.sdkgen.networking.fetchoptions.RequestDataFactory;
import com.box.sdkgen.schemas.postoauth2token.PostOAuth2Token;
import com.box.sdkgen.schemas.postoauth2token.PostOAuth2TokenGrantTypeField;
import com.box.sdkgen.serialization.json.JsonManager;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.Map;

/**
* Builds the body of a JWT bearer access token request. Each call signs a new assertion with a
* unique `jti`, so a retried request is not rejected as a replay.
*/
public class JwtAccessTokenDataFactory implements RequestDataFactory {

/** JWT configuration used to sign the assertion */
public final JWTConfig config;

/** The ID of the user or enterprise to authenticate as */
public String subjectId;

/** The type of the subject ID, either 'user' or 'enterprise' */
public String subjectType;

public JwtAccessTokenDataFactory(JWTConfig config) {
this.config = config;
}

protected JwtAccessTokenDataFactory(Builder builder) {
this.config = builder.config;
this.subjectId = builder.subjectId;
this.subjectType = builder.subjectType;
}

/** Creates the access token request body with a newly signed JWT assertion. */
@Override
public JsonNode create() {
Map<String, Object> claims =
mapOf(
entryOf("exp", getEpochTimeInSeconds() + 30),
entryOf("box_sub_type", this.subjectType));
JwtSignOptions jwtOptions =
new JwtSignOptions(
this.config.getAlgorithm(),
"https://api.box.com/oauth2/token",
this.config.getClientId(),
this.subjectId,
getUuid(),
this.config.getJwtKeyId(),
this.config.getPrivateKeyDecryptor());
JwtKey jwtKey = new JwtKey(this.config.getPrivateKey(), this.config.getPrivateKeyPassphrase());
String assertion = createJwtAssertion(claims, jwtKey, jwtOptions);
PostOAuth2Token requestBody =
new PostOAuth2Token.Builder(
PostOAuth2TokenGrantTypeField.URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER)
.assertion(assertion)
.clientId(this.config.getClientId())
.clientSecret(this.config.getClientSecret())
.build();
return JsonManager.serialize(requestBody);
}

public JWTConfig getConfig() {
return config;
}

public static class Builder {

protected final JWTConfig config;

protected String subjectId;

protected String subjectType;

public Builder(JWTConfig config) {
this.config = config;
}

public Builder subjectId(String subjectId) {
this.subjectId = subjectId;
return this;
}

public Builder subjectType(String subjectType) {
this.subjectType = subjectType;
return this;
}

public JwtAccessTokenDataFactory build() {
return new JwtAccessTokenDataFactory(this);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ public static String createJwtAssertion(

jwtClaims.setSubject(jwtOptions.getSubject());
jwtClaims.setClaim("box_sub_type", claims.get("box_sub_type"));
jwtClaims.setGeneratedJwtId(64);
jwtClaims.setJwtId(jwtOptions.getJwtid());

JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(jwtClaims.toJson());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,6 @@ public FetchResponse fetch(FetchOptions options) {
NetworkSession networkSession =
options.getNetworkSession() == null ? new NetworkSession() : options.getNetworkSession();

FetchOptions fetchOptions =
networkSession.getInterceptors().stream()
.reduce(
options,
(modifiedOptions, interceptor) -> interceptor.beforeRequest(modifiedOptions),
(o1, o2) -> o2);

boolean authenticationNeeded = false;
Request request;
FetchResponse fetchResponse = new FetchResponse.Builder(0, new TreeMap<>()).build();
Expand All @@ -153,6 +146,20 @@ public FetchResponse fetch(FetchOptions options) {
boolean shouldRetry = false;

while (true) {
FetchOptions attemptOptions =
(attemptNumber > 1 || numberOfRetriesOnException > 0 || options.getData() == null)
&& options.getDataFactory() != null
? withData(options, options.getDataFactory().create())
: options;
FetchOptions fetchOptions = applyInterceptors(attemptOptions, networkSession);
if (fetchOptions.getDataFactory() != null
&& options.getDataFactory() == null
&& (attemptNumber > 1
|| numberOfRetriesOnException > 0
|| fetchOptions.getData() == null)) {
fetchOptions = withData(fetchOptions, fetchOptions.getDataFactory().create());
}

request = prepareRequest(fetchOptions, authenticationNeeded, networkSession);

Response response = null;
Expand Down Expand Up @@ -268,6 +275,31 @@ public FetchResponse fetch(FetchOptions options) {
}
}

private static FetchOptions applyInterceptors(
FetchOptions options, NetworkSession networkSession) {
return networkSession.getInterceptors().stream()
.reduce(
options,
(modifiedOptions, interceptor) -> interceptor.beforeRequest(modifiedOptions),
(o1, o2) -> o2);
}

private static FetchOptions withData(FetchOptions options, JsonNode data) {
return new FetchOptions.Builder(options.getUrl(), options.getMethod())
.params(options.getParams())
.headers(options.getHeaders())
.data(data)
.dataFactory(options.getDataFactory())
.fileStream(options.getFileStream())
.multipartData(options.getMultipartData())
.contentType(options.getContentType())
.responseFormat(options.getResponseFormat())
.auth(options.getAuth())
.networkSession(options.getNetworkSession())
.followRedirects(options.getFollowRedirects())
.build();
}

private static Request prepareRequest(
FetchOptions options, boolean reauthenticate, NetworkSession networkSession) {
Request.Builder requestBuilder = new Request.Builder().url(options.getUrl());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ public class FetchOptions {
/** Request body of the request */
public JsonNode data;

/**
* Factory that builds a request body when `data` is not provided and rebuilds it for each retry.
*/
public RequestDataFactory dataFactory;

/** Stream data of the request */
public InputStream fileStream;

Expand Down Expand Up @@ -63,6 +68,7 @@ protected FetchOptions(Builder builder) {
this.params = builder.params;
this.headers = builder.headers;
this.data = builder.data;
this.dataFactory = builder.dataFactory;
this.fileStream = builder.fileStream;
this.multipartData = builder.multipartData;
this.contentType = builder.contentType;
Expand Down Expand Up @@ -92,6 +98,10 @@ public JsonNode getData() {
return data;
}

public RequestDataFactory getDataFactory() {
return dataFactory;
}

public InputStream getFileStream() {
return fileStream;
}
Expand Down Expand Up @@ -132,6 +142,8 @@ public static class Builder {

protected JsonNode data;

protected RequestDataFactory dataFactory;

protected InputStream fileStream;

protected List<MultipartItem> multipartData;
Expand Down Expand Up @@ -166,6 +178,11 @@ public Builder data(JsonNode data) {
return this;
}

public Builder dataFactory(RequestDataFactory dataFactory) {
this.dataFactory = dataFactory;
return this;
}

public Builder fileStream(InputStream fileStream) {
this.fileStream = fileStream;
return this;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.box.sdkgen.networking.fetchoptions;

import com.fasterxml.jackson.databind.JsonNode;

public interface RequestDataFactory {

/** Creates a new request body */
JsonNode create();
}
Loading
Loading