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": "4.20.0" }
{ "engineHash": "6772894", "specHash": "7f8494a", "version": "4.20.0" }
113 changes: 84 additions & 29 deletions box_sdk_gen/box/jwt_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from box_sdk_gen.serialization.json import deserialize

from box_sdk_gen.serialization.json import serialize

from typing import List

from box_sdk_gen.schemas.post_o_auth_2_token import PostOAuth2TokenGrantTypeField
Expand All @@ -30,6 +32,14 @@

from box_sdk_gen.serialization.json import SerializedData

from box_sdk_gen.networking.fetch_options import FetchOptions

from box_sdk_gen.networking.fetch_options import RequestDataFactory

from box_sdk_gen.networking.fetch_options import ResponseFormat

from box_sdk_gen.networking.fetch_response import FetchResponse

from box_sdk_gen.internal.utils import get_uuid

from box_sdk_gen.internal.utils import read_text_from_file
Expand Down Expand Up @@ -269,36 +279,32 @@ def from_config_file(
)


class BoxJWTAuth(Authentication):
def __init__(self, config: JWTConfig, **kwargs):
class JwtAccessTokenDataFactory(RequestDataFactory):
def __init__(
self,
config: JWTConfig,
*,
subject_id: Optional[str] = None,
subject_type: Optional[str] = None,
**kwargs
):
"""
:param config: An object containing all JWT configuration to use for authentication
:param config: JWT configuration used to sign the assertion
:type config: JWTConfig
:param subject_id: The ID of the user or enterprise to authenticate as, defaults to None
:type subject_id: Optional[str], optional
:param subject_type: The type of the subject ID, either 'user' or 'enterprise', defaults to None
:type subject_type: Optional[str], optional
"""
super().__init__(**kwargs)
self.config = config
self.token_storage = self.config.token_storage
self.subject_id = (
self.config.enterprise_id
if not self.config.enterprise_id == None
else self.config.user_id
)
self.subject_type = (
'enterprise' if not self.config.enterprise_id == None else 'user'
)
self.subject_id = subject_id
self.subject_type = subject_type

def refresh_token(
self, *, network_session: Optional[NetworkSession] = None
) -> AccessToken:
def create(self) -> SerializedData:
"""
Get new access token using JWT auth.
:param network_session: An object to keep network session state, defaults to None
:type network_session: Optional[NetworkSession], optional
Creates the access token request body with a newly signed JWT assertion.
"""
if is_browser():
raise BoxSDKError(
message='JWT auth is not supported in browser environment.'
)
alg: JwtAlgorithm = (
self.config.algorithm
if not self.config.algorithm == None
Expand All @@ -321,17 +327,66 @@ def refresh_token(
key=self.config.private_key, passphrase=self.config.private_key_passphrase
)
assertion: str = create_jwt_assertion(claims, jwt_key, jwt_options)
auth_manager: AuthorizationManager = AuthorizationManager(
network_session=(
network_session if not network_session == None else NetworkSession()
)
)
token: AccessToken = auth_manager.request_access_token(
PostOAuth2TokenGrantTypeField.URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER,
request_body: PostOAuth2Token = PostOAuth2Token(
grant_type=PostOAuth2TokenGrantTypeField.URN_IETF_PARAMS_OAUTH_GRANT_TYPE_JWT_BEARER,
assertion=assertion,
client_id=self.config.client_id,
client_secret=self.config.client_secret,
)
return serialize(request_body)


class BoxJWTAuth(Authentication):
def __init__(self, config: JWTConfig, **kwargs):
"""
:param config: An object containing all JWT configuration to use for authentication
:type config: JWTConfig
"""
super().__init__(**kwargs)
self.config = config
self.token_storage = self.config.token_storage
self.subject_id = (
self.config.enterprise_id
if not self.config.enterprise_id == None
else self.config.user_id
)
self.subject_type = (
'enterprise' if not self.config.enterprise_id == None else 'user'
)

def refresh_token(
self, *, network_session: Optional[NetworkSession] = None
) -> AccessToken:
"""
Get new access token using JWT auth.
:param network_session: An object to keep network session state, defaults to None
:type network_session: Optional[NetworkSession], optional
"""
if is_browser():
raise BoxSDKError(
message='JWT auth is not supported in browser environment.'
)
network_session_to_use: NetworkSession = (
network_session if not network_session == None else NetworkSession()
)
data_factory: JwtAccessTokenDataFactory = JwtAccessTokenDataFactory(
config=self.config,
subject_id=self.subject_id,
subject_type=self.subject_type,
)
response: FetchResponse = network_session_to_use.network_client.fetch(
FetchOptions(
url=''.join(
[network_session_to_use.base_urls.base_url, '/oauth2/token']
),
method='POST',
data_factory=data_factory,
content_type='application/x-www-form-urlencoded',
response_format=ResponseFormat.JSON,
network_session=network_session_to_use,
)
)
token: AccessToken = deserialize(response.data, AccessToken)
self.token_storage.store(token)
return token

Expand Down
15 changes: 15 additions & 0 deletions box_sdk_gen/networking/box_network_client.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import copy
import io

import time
Expand Down Expand Up @@ -89,6 +90,7 @@ def fetch(self, options: 'FetchOptions') -> FetchResponse:
multipart_streams_positions = self._get_multipart_stream_positions(options)

while True:
options = self._prepare_options_for_attempt(options, attempt_nr)
request: APIRequest = self._prepare_request(
options=options, reauthenticate=response.reauthentication_needed
)
Expand Down Expand Up @@ -150,6 +152,19 @@ def fetch(self, options: 'FetchOptions') -> FetchResponse:
request=request, response=response, data_sanitizer=data_sanitizer
)

@staticmethod
def _prepare_options_for_attempt(
options: 'FetchOptions', attempt_number: int
) -> 'FetchOptions':
if options.data_factory is None or (
attempt_number == 1 and options.data is not None
):
return options

retry_options = copy.copy(options)
retry_options.data = options.data_factory.create()
return retry_options

def _prepare_request(
self, options: 'FetchOptions', reauthenticate: bool = False
) -> APIRequest:
Expand Down
18 changes: 18 additions & 0 deletions box_sdk_gen/networking/fetch_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from typing import Optional

from abc import abstractmethod

from typing import Dict

from typing import List
Expand Down Expand Up @@ -56,6 +58,18 @@ def __init__(
self.content_type = content_type


class RequestDataFactory:
def __init__(self):
pass

@abstractmethod
def create(self) -> SerializedData:
"""
Creates a new request body
"""
pass


class FetchOptions:
def __init__(
self,
Expand All @@ -65,6 +79,7 @@ def __init__(
params: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
data: Optional[SerializedData] = None,
data_factory: Optional[RequestDataFactory] = None,
file_stream: Optional[ByteStream] = None,
multipart_data: Optional[List[MultipartItem]] = None,
content_type: str = 'application/json',
Expand All @@ -84,6 +99,8 @@ def __init__(
:type headers: Optional[Dict[str, str]], optional
:param data: Request body of the request, defaults to None
:type data: Optional[SerializedData], optional
:param data_factory: Factory that builds a request body when `data` is not provided and rebuilds it for each retry., defaults to None
:type data_factory: Optional[RequestDataFactory], optional
:param file_stream: Stream data of the request, defaults to None
:type file_stream: Optional[ByteStream], optional
:param multipart_data: Multipart data of the request, defaults to None
Expand All @@ -104,6 +121,7 @@ def __init__(
self.params = params
self.headers = headers
self.data = data
self.data_factory = data_factory
self.file_stream = file_stream
self.multipart_data = multipart_data
self.content_type = content_type
Expand Down
2 changes: 2 additions & 0 deletions docs/box_sdk_gen/client.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,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 `data_factory`. `data_factory.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
Loading
Loading