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

Expose tasks from async methods #742

Merged
merged 3 commits into from
Aug 20, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions Box.V2.Samples.Core.AppUser.Create/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ private async Task ExecuteMainAsync()
var session = new BoxJWTAuth(config);

// client with permissions to manage application users
var adminToken = session.AdminToken();
var adminToken = await session.AdminTokenAsync();
var client = session.AdminClient(adminToken);

var user = await CreateNewUser(client);
Console.WriteLine("New app user created with Id = {0}", user.Id);

// user client with access to user's data (folders, files, etc)
var userToken = session.UserToken(user.Id);
var userToken = await session.UserTokenAsync(user.Id);
var userClient = session.UserClient(userToken, user.Id);

// root folder has id = 0
Expand Down
2 changes: 1 addition & 1 deletion Box.V2.Samples.Core.HttpProxy/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ static void Main(string[] args)

var boxJWT = new BoxJWTAuth(boxConfig);

var adminToken = boxJWT.AdminToken();
var adminToken = boxJWT.AdminTokenAsync().Result;
var adminClient = boxJWT.AdminClient(adminToken);

var items = adminClient.FoldersManager.GetFolderItemsAsync("0", 500).Result;
Expand Down
4 changes: 2 additions & 2 deletions Box.V2.Samples.JWTAuth/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ static async Task MainAsync()
.Build();
var boxJWT = new BoxJWTAuth(boxConfig);

var adminToken = boxJWT.AdminToken();
var adminToken = await boxJWT.AdminTokenAsync();
Console.WriteLine("Admin Token: " + adminToken);
Console.WriteLine();

Expand All @@ -61,7 +61,7 @@ static async Task MainAsync()
var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);
Console.WriteLine("Created App User");

var userToken = boxJWT.UserToken(appUser.Id);
var userToken = await boxJWT.UserTokenAsync(appUser.Id);
var userClient = boxJWT.UserClient(userToken, appUser.Id);

var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();
Expand Down
4 changes: 2 additions & 2 deletions Box.V2.Samples.TransactionalAuth/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ private static async Task MainAsync(string token, string fileId, string folderId
var tokenExchange = new TokenExchange(token, scope);

// Check resource to be optional
var token1 = tokenExchange.Exchange();
var token1 = await tokenExchange.ExchangeAsync();
var client1 = CreateClientByToken(token1);

// Set resource
tokenExchange.SetResource(resource);
var token2 = tokenExchange.Exchange();
var token2 = await tokenExchange .ExchangeAsync();
var client2 = CreateClientByToken(token2);
try
{
Expand Down
4 changes: 2 additions & 2 deletions Box.V2.Test.Integration/BoxAuthTestIntegration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ public class BoxAuthTestIntegration : BoxResourceManagerTestIntegration
public const string passphrase = "YOUR_PASSPHRASE";

[TestMethod]
public void retriesWithNewJWTAssertionOnErrorResponseAndSucceeds()
public async Task retriesWithNewJWTAssertionOnErrorResponseAndSucceeds()
{
var config = new BoxConfigBuilder(ClientId, ClientSecret, EnterpriseId, privateKey, passphrase, publicKeyID)
.Build();
var session = new BoxJWTAuth(config);
var adminToken = session.AdminToken();
var adminToken = await session.AdminTokenAsync();
adminClient = session.AdminClient(adminToken);
}
}
Expand Down
4 changes: 2 additions & 2 deletions Box.V2.Test.Integration/BoxResourceManagerTestIntegration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static void Initialize(TestContext testContext)

// create a new app user
// client with permissions to manage application users
var adminToken = session.AdminToken();
var adminToken = session.AdminTokenAsync().Result;
adminClient = session.AdminClient(adminToken);

var user = CreateNewUser(adminClient).Result;
Expand All @@ -60,7 +60,7 @@ public static void Initialize(TestContext testContext)
Debug.WriteLine("New app user created : " + userId);

// user client with access to user's data (folders, files, etc)
userToken = session.UserToken(userId);
userToken = session.UserTokenAsync(userId).Result;
userClient = session.UserClient(userToken, userId);
}
}
Expand Down
4 changes: 2 additions & 2 deletions Box.V2.Test.Integration/BoxTokenExchangeTestIntegration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task TokenExchange_LiveSession()
var tokenExchange = new TokenExchange(token, scopes);

// Check resource to be optional
var token1 = tokenExchange.Exchange();
var token1 = tokenExchange.ExchangeAsync().Result;
var client1 = CreateClientByToken(token1);

// Should be able to access the file
Expand All @@ -49,7 +49,7 @@ public async Task TokenExchange_LiveSession()

// Set resource
tokenExchange.SetResource(resource);
var token2 = tokenExchange.Exchange();
var token2 = tokenExchange.ExchangeAsync().Result;
var client2 = CreateClientByToken(token2);
try
{
Expand Down
12 changes: 6 additions & 6 deletions Box.V2.Test/BoxJWTAuthTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public BoxJWTAuthTest()

[TestMethod]
[TestCategory("CI-UNIT-TEST")]
public void GetToken_ValidSession()
public async Task GetToken_ValidSession()
{
// Arrange
_handler.Setup(h => h.ExecuteAsyncWithoutRetry<OAuthSession>(It.IsAny<BoxRequest>()))
Expand All @@ -47,7 +47,7 @@ public void GetToken_ValidSession()
})); ;

// Act
String accessToken = _jwtAuth.AdminToken();
String accessToken = await _jwtAuth.AdminTokenAsync();

// Assert
Assert.AreEqual(accessToken, "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl");
Expand All @@ -56,7 +56,7 @@ public void GetToken_ValidSession()
[TestMethod]
[TestCategory("CI-UNIT-TEST")]
[ExpectedException(typeof(BoxException))]
public void GetToken_MaxRetries_Exception()
public async Task GetToken_MaxRetries_Exception()
{
// Arrange
_handler.SetupSequence(h => h.ExecuteAsyncWithoutRetry<OAuthSession>(It.IsAny<BoxRequest>()))
Expand Down Expand Up @@ -97,12 +97,12 @@ public void GetToken_MaxRetries_Exception()
}));

// Act
String accessToken = _jwtAuth.AdminToken();
String accessToken = await _jwtAuth.AdminTokenAsync();
}

[TestMethod]
[TestCategory("CI-UNIT-TEST")]
public void GetToken_Retries_ValidSession()
public async Task GetToken_Retries_ValidSession()
{
// Arrange
_handler.SetupSequence(h => h.ExecuteAsyncWithoutRetry<OAuthSession>(It.IsAny<BoxRequest>()))
Expand All @@ -123,7 +123,7 @@ public void GetToken_Retries_ValidSession()
}));

// Act
String accessToken = _jwtAuth.AdminToken();
String accessToken = await _jwtAuth.AdminTokenAsync();

// Assert
Assert.AreEqual(accessToken, "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl");
Expand Down
7 changes: 4 additions & 3 deletions Box.V2/Auth/Token/TokenExchange.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using Box.V2.Config;
using Box.V2.Config;
using Box.V2.Request;
using Box.V2.Converter;
using Box.V2.Services;
using Box.V2.Extensions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Box.V2.Auth.Token
{
Expand Down Expand Up @@ -65,7 +66,7 @@ public void SetResource(string resourceUrl)
/// Get a down scoped token.
/// </summary>
/// <returns>The down scoped access token.</returns>
public string Exchange()
public async Task<string> ExchangeAsync()
{
BoxRequest boxRequest = new BoxRequest(new Uri(Constants.BoxApiHostUriString), Constants.AuthTokenEndpointString)
.Method(RequestMethod.Post)
Expand All @@ -85,7 +86,7 @@ public string Exchange()
var converter = new BoxJsonConverter();
var service = new BoxService(handler);

IBoxResponse<OAuthSession> boxResponse = service.ToResponseAsync<OAuthSession>(boxRequest).Result;
IBoxResponse<OAuthSession> boxResponse = await service.ToResponseAsync<OAuthSession>(boxRequest).ConfigureAwait(false);
boxResponse.ParseResults(converter);

return boxResponse.ResponseObject.AccessToken;
Expand Down
17 changes: 9 additions & 8 deletions Box.V2/JWTAuth/BoxJWTAuth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Box.V2.JWTAuth
{
Expand Down Expand Up @@ -133,21 +134,21 @@ public BoxClient UserClient(string userToken, string userId)
/// Get admin token by posting data to auth url
/// </summary>
/// <returns>Admin token</returns>
public string AdminToken()
public async Task<string> AdminTokenAsync()
{
return this.GetToken(ENTERPRISE_SUB_TYPE, this.boxConfig.EnterpriseId);
return await this.GetTokenAsync(ENTERPRISE_SUB_TYPE, this.boxConfig.EnterpriseId).ConfigureAwait(false);
}
/// <summary>
/// Once you have created an App User, you can request a User Access Token via the App Auth feature, which will return the OAuth 2.0 access token for the specified App User.
/// </summary>
/// <param name="userId">Id of the user</param>
/// <returns>User token</returns>
public string UserToken(string userId)
public async Task<string> UserTokenAsync(string userId)
{
return this.GetToken(USER_SUB_TYPE, userId);
return await this.GetTokenAsync(USER_SUB_TYPE, userId).ConfigureAwait(false);
}

private string GetToken(string subType, string subId)
private async Task<string> GetTokenAsync(string subType, string subId)
{
int retryCounter = 0;
ExponentialBackoff expBackoff = new ExponentialBackoff();
Expand All @@ -159,7 +160,7 @@ private string GetToken(string subType, string subId)
{
try
{
result = JWTAuthPost(assertion);
result = await JWTAuthPostAsync(assertion).ConfigureAwait(false);
return result.AccessToken;
}
catch (BoxException ex)
Expand Down Expand Up @@ -267,7 +268,7 @@ private string ConstructJWTAssertion(string sub, string boxSubType, DateTime? no
return assertion;
}

private OAuthSession JWTAuthPost(string assertion)
private async Task<OAuthSession> JWTAuthPostAsync(string assertion)
{
BoxRequest boxRequest = new BoxRequest(this.boxConfig.BoxApiHostUri, Constants.AuthTokenEndpointString)
.Method(RequestMethod.Post)
Expand All @@ -278,7 +279,7 @@ private OAuthSession JWTAuthPost(string assertion)
.Payload(Constants.RequestParameters.ClientSecret, this.boxConfig.ClientSecret);

var converter = new BoxJsonConverter();
IBoxResponse<OAuthSession> boxResponse = this.boxService.ToResponseAsyncWithoutRetry<OAuthSession>(boxRequest).Result;
IBoxResponse<OAuthSession> boxResponse = await this.boxService.ToResponseAsyncWithoutRetry<OAuthSession>(boxRequest).ConfigureAwait(false);
boxResponse.ParseResults(converter);

return boxResponse.ResponseObject;
Expand Down
6 changes: 3 additions & 3 deletions Box.V2/JWTAuth/JWTAuthRepository.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Box.V2.Auth;
using Box.V2.Auth;
using System;
using System.Threading.Tasks;

Expand Down Expand Up @@ -75,11 +75,11 @@ public async Task<OAuthSession> RefreshAccessTokenAsync(string accessToken)

if (UserId != null)
{
session = this.BoxJWTAuth.Session(this.BoxJWTAuth.UserToken(this.UserId));
session = this.BoxJWTAuth.Session(await this.BoxJWTAuth.UserTokenAsync(this.UserId).ConfigureAwait(false));
}
else
{
session = this.BoxJWTAuth.Session(this.BoxJWTAuth.AdminToken());
session = this.BoxJWTAuth.Session(await this.BoxJWTAuth.AdminTokenAsync().ConfigureAwait(false));
}

this.Session = session;
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
**Breaking changes:**
- Extract interfaces for BoxClient and Managers to improve testability ([#603](https://github.com/box/box-windows-sdk-v2/pull/603))
- Add BoxConfigBuilder and make BoxConfig immutable ([#737](https://github.com/box/box-windows-sdk-v2/pull/737))
- Expose tasks from async methods ([#742](https://github.com/box/box-windows-sdk-v2/pull/742))

**New Features and Enhancements:**
- Add ability to get files under retention for assignment and file versions under retention for assignment ([#734](https://github.com/box/box-windows-sdk-v2/pull/734))
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ var boxJWT = new BoxJWTAuth(boxConfig);

##### Authenticate
```c#
var adminToken = boxJWT.AdminToken(); //valid for 60 minutes so should be cached and re-used
var adminToken = await boxJWT.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used
var adminClient = boxJWT.AdminClient(adminToken);
```

Expand All @@ -75,7 +75,7 @@ var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccess
var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);

//get a user client
var userToken = boxJWT.UserToken(appUser.Id); //valid for 60 minutes so should be cached and re-used
var userToken = await boxJWT.UserTokenAsync(appUser.Id); //valid for 60 minutes so should be cached and re-used
var userClient = boxJWT.UserClient(userToken, appUser.Id);

//for example, look up the app user's details
Expand Down Expand Up @@ -294,7 +294,7 @@ Using the admin token we can make a call to retrieve all users or a specific use
var boxConfig = new BoxConfigBuilder(<Client_Id>, <Client_Secret>, <Enterprise_Id>, <Private_Key>, <JWT_Private_Key_Password>, <JWT_Public_Key_Id>). Build();
var boxJWT = new BoxJWTAuth(boxConfig);

var adminToken = boxJWT.AdminToken();
var adminToken = await boxJWT.AdminTokenAsync();
var adminClient = boxJWT.AdminClient(adminToken);

var boxUsers = await adminClient.UsersManager.GetEnterpriseUsersAsync();
Expand Down
10 changes: 5 additions & 5 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Service Account:
```c#
var config = BoxConfigBuilder.CreateFromJsonString(jsonConfig).Build();
var session = new BoxJWTAuth(config);
var adminToken = session.AdminToken(); //valid for 60 minutes so should be cached and re-used
var adminToken = await session.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used
BoxClient adminClient = session.AdminClient(adminToken);
```

Expand All @@ -75,7 +75,7 @@ to the `BoxConfigBuilder` constructor:
```c#
var boxConfig = new BoxConfigBuilder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET", "YOUR_ENTERPRISE_ID", "ENCRYPTED_PRIVATE_KEY", "PRIVATE_KEY_PASSWORD", "PUBLIC_KEY_ID").Build();
var boxJWT = new BoxJWTAuth(boxConfig);
var adminToken = boxJWT.AdminToken(); //valid for 60 minutes so should be cached and re-used
var adminToken = await boxJWT.AdminTokenAsync(); //valid for 60 minutes so should be cached and re-used
BoxClient adminClient = boxJWT.AdminClient(adminToken);
adminClient.Auth.SessionAuthenticated += delegate(object o, SessionAuthenticatedEventArgs e)
{
Expand All @@ -99,7 +99,7 @@ instance as in the above examples, similarly to creating a Service Account clien
<!-- sample x_auth init_with_jwt_with_user_id -->
```c#
var appUserId = "12345";
var userToken = boxJWT.UserToken(appUserID); //valid for 60 minutes so should be cached and re-used
var userToken = await boxJWT.UserTokenAsync(appUserID); //valid for 60 minutes so should be cached and re-used
BoxClient appUserClient = boxJWT.UserClient(userToken, appUserId);
appUserClient.Auth.SessionAuthenticated += delegate(object o, SessionAuthenticatedEventArgs e)
{
Expand Down Expand Up @@ -194,13 +194,13 @@ scope, restricted to a single file, suitable for the
```c#
var exchanger = new TokenExchange(client.Auth.Session.AccessToken, "item_preview");
exchanger.SetResource("https://api.box.com/2.0/files/123456789");
string downscopedToken = exchanger.Exchange();
string downscopedToken = await exchanger.ExchangeAsync();
```

To exchange the client's token for one with scopes to upload and delete items, but not to view their contents,
which would be suitable for an less-trusted server-side process;
```c#
var scopes = new List<string>() { "item_upload", "item_download" };
var exchanger = new TokenExchange(client.Auth.Session.AccessToken, scopes);
string downscopedToken = exchanger.Exchange();
string downscopedToken = await exchanger.ExchangeAsync();
```