Skip to main content
Box Employee
May 22, 2025 9:04 AM UTC
Question

Questions for BOX App User coding

A.  This is the method used to authenticate the old app which was using standard users and synchronizing to the individual logged in users Box account:
  [BOXContentClient setClientID:@xyz" clientSecret:@abc"];
  [[BOXContentClient defaultClient] authenticateInAppWithCompletionBlock:^(BOXUser *user, NSError *error) {
    if (error == nil) {
      NSLog(@"Logged in user: %@", user.login);
    } else {
      NSLog(@"Error occurred authenticating with Box: %@", error.description);
    }
  }];
 
If I merely replace the first line with the line below, which contains the clientID and clientSecret for the new app, it will not authenticate.
  [BOXContentClient setClientID:@elm" clientSecret:@"jul"];
 
Since we are wanting to use AppUsers instead of standard users, the documentation leads me to believe that we cannot use this method of authenticating with the new app.  Is that the case?
 
B.  The documentation leads you through the various things to do for oAuth2 but there is no clear, concise code sample showing how to create an oAuth2 session and authenticate.  Can you provide?
 
C.  If not, here is the code from some of the various attempts I have tried.  I have imported the JWT pod into the application and tried to use it to create a JWT but when the encodePayload is called, it tries to connect and the Box error screen appears.  It isnt clear from the documentation what I would even do with the JWT if it were created successfully.  Do I need to create a BoxParallelOAuth2Session or can I call the [BoxContentClient defaultClient] authenticateInAppWithCompletionBlock method?  Again, a simple set of example code would be niceusing our clientID, clientSecret, AppID, etc would be even better.
 
Code that doesnt work:
  @try{
    NSString *jti = [Guid newGuidString];
    NSDate *exp = [NSDate date];
    NSDictionary *payload = @{@"iss": @abcdef", @"sub": @***@example.com", @"box_sub_type": @"user", @"aud": @"https://api.box.com/oauth2/token", @"jti": jti, @"exp": exp};
    NSString *secret = @opqrst";

    19 replies

    Box Employee
    May 22, 2025 9:04 AM UTC

     I answered your questions by letter below. Please let me know if my answers make sense? 

     

    A. The App User authentication process is slightly different than the standard user authentication process on mobile. For App User authentication, you would have to implement the App User OAuth flow on the server, and then pass the app user access token back to the device.

     

    You can use one of our SDKs like our Java, .NET, or Ruby ones to implement the App User OAuth flow on the server. 

     

    Once you get the app user token back to the device, you would pass the app user access token to the fetchAccessTokenWithCompletion method. Here is the iOS documentation for this. 

     

     

    - (void)fetchAccessTokenWithCompletion:(void (^)(NSString *, NSDate, NSError *))completion
    {
      // Do things to retrieve access token and access token expiration date.
      completion(accessToken, accessTokenExpiration, error);
    }

     

     

    B. I agree we need to add a concise code sample for authentication on the documentation site. 

     

    Here is documentation from our Java SDK that shows how to create an app user and then get an app user access token using the SDK. CreateAppUser is the class that implements this functionality in the Java SDK. 

     

    C. Same answer as A

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    murtzathanks for this advicepassing it over to the developer (I am the product manager) now for reviewwill get back to you with a report on how it worked tomorrowthanks a million, manreally appreciate it
    Best,Tom

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    Murtza,

     

    One more question... and probably a dumb one.

    When you talk about the servier in this configuration are you talking about BOX?

    This app resides on the Apple devices and is not hosted anywhere.

    BOX is the file destination and repository that communicates with the app.

    THanks for your patience and the quick reply.

    Appreciate it,

    Tom

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

     I wanted to note a correction to my earlier answer. You would be implementing authentication using JWT (not App User OAuth as I wrote). The OAuth process is designed to be used with Standard Box Users (Managed Users). The JWT auth process is designed to be used with App Users. Sorry about the confusion!

     

    To answer your second question, there will be three parts for this use case, which includes the mobile app, the Box Platform, and the server. The reason you want to have a server for this use case is to be more secure. 

     

    The App User auth token lets you access the App User's files stored in the Box Platform. When you generate the App User auth token using JWT, you will be making a request to the Box Platform API with client secret that is registered to your Box App. If you store the client secret within your app and somebody reverse engineers it, they could potentially create more auth tokens with your client secret. So to be more secure, you would implement the JWT auth process on the server, pass the App User auth token to the mobile app, and then request the App User's files.

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    OK

    That explains why the OAuth didn't work last night.

    Thanks.

     

    So to speed the process, could you please send some sample code (from any app, or test app or whatever) of constructing the JWT (in 'BOX" terms) and authenticating it.

     

    Here is a sample of our developer's code for the JWT including the original question (C). Please have a look and identify where it is incorrect, and please provide a correct code sample for this function. Thanks much.

     

    C.  If not, here is the code from some of the various attempts I have tried.  I have imported the JWT pod into the application and tried to use it to create a JWT but when the encodePayload is called, it tries to connect and the Box error screen appears.  It isnt clear from the documentation what I would even do with the JWT if it were created successfully.  Do I need to create a BoxParallelOAuth2Session or can I call the [BoxContentClient defaultClient] authenticateInAppWithCompletionBlock method?  Again, a simple set of example code would be niceusing our clientID, clientSecret, AppID, etc would be even better.
     
    Code that doesnt work:
      @try{
        NSString *jti = [Guid newGuidString];
        NSDate *exp = [NSDate date];
        NSDictionary *payload = @{@"iss": @abcdef", @"sub": @***@example.com", @"box_sub_type": @"user", @"aud": @"https://api.box.com/oauth2/token", @"jti": jti, @"exp": exp};
        NSString *secret = @opqrst";
    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    Here's an example from our Ruby SDK that show how to construct the JWT assertion. 

     

      def self.jwt_assertion(private_key, iss, sub, box_sub_type, public_key_id)
        payload = {
          iss: iss,
          sub: sub,
          box_sub_type: box_sub_type,
          aud: "https://api.box.com/oauth2/token",
          jti: SecureRandom.hex(64),
          exp: (Time.now.utc + 10).to_i
        }
    
        additional_headers = {}
        additional_headers['kid'] = public_key_id unless public_key_id.nil?
        
        JWT.encode(payload, private_key, "RS256", additional_headers)
      end

    If you use one of our SDKs, the SDK will handle building the JWT assertion for you.  For example with the Ruby SDK, you would just call the get_user_token method, which returns the App User access token and abstracts away the underlying details.

     

    Boxr::get_user_token(user_id, private_key: ENV['JWT_PRIVATE_KEY'], private_key_password: ENV['JWT_PRIVATE_KEY_PASSWORD'], public_key_id: ENV['JWT_PUBLIC_KEY_ID'], client_id: ENV['BOX_CLIENT_ID'], client_secret: ENV['BOX_CLIENT_SECRET'])
    

     

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    Murza

     

    thanks muchnman

    do you have the same thing in iOS?

    our app is a Universal app for Apple devices

    appreciate it

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    I'm getting the following error as I try to authenticate:

    Terminating app due to uncaught exception 'You cannot use 'defaultClient' if multiple users have established a session.', reason: 'Specify a user through clientForUser:'

     

    I have tried multiple ways to authenticate but here is the latest.  It breaks on the bolded line with the error.  (NOTE:  I'm just using one of the users passed down from Box to ensure that I'm grabbing a valid user for the moment.  I'll handle user selection later, if & when I can ever get this to authenticate).

     

    Please advise:

     

    Erroneous code:

      [BOXContentClient setClientID:@"abc" clientSecret:@"xyz"];

      BOXContentClient *client;

     

      BOXUserMini *currentUser;

      for (BOXUser *user in [BOXContentClient users]) {

        BOXContentClient *clnt = [BOXContentClient clientForUser:user];

        if([clnt.user.name isEqualToString:@"***@example.com"]){

          currentUser = clnt.user;

        }

      }

      NSLog(@"CurrentUser: %@", currentUser.name);

      [[BOXContentClient clientForUser:currentUser] authenticateWithCompletionBlock:^(BOXUser *user, NSError *error) {

        if (error) {

          if ([error.domain isEqualToString:BOXContentSDKErrorDomain] && error.code == BOXContentSDKAPIUserCancelledError) {

            BOXLog(@"Authentication was cancelled, please try again.");

          } else {

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil

                                                                message:@"Login failed, please try again"

                                                               delegate:nil

                                                      cancelButtonTitle:nil

                                                      otherButtonTitles:@"OK", nil];

            [alertView show];

          }

        } else {

          BOXContentClient *tmpClient = [BOXContentClient clientForUser:user];

           }

      }];

     

     

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

      Just wanted to highlight that we do not recommend developers authenticate App Users from their mobile apps. This is why we do not provide this functionality from our iOS SDK.

     

    If somebody reverse engineers a mobile app that is authenticating App Users directly from the mobile app, they could potentially get access to that developer's Box API client secret and private key. Once somebody has access to these credentials, they can get access to the data stored in that developer's Box Platform instance.

     

    To mitigate this risk, we recommend generating an App User access token on the server and passing this access token to the mobile app.

     

    We have SDKs that can be used to easily generate the App User access token on the server. Here are links to our SDKs:

    Java SDK

    .NET SDK

    Ruby SDK

    Python SDK

     

    Please let me know if one the SDKs above will work in your development environment? I am happy to provide sample code in that language.

    Translate
    Box Employee
    May 22, 2025 9:04 AM UTC

    Murtza,
    Thanks much for that clarification. This explains a bunch. If we could get the sample code in .NET SDK that would be great
    It will probably help us figure out the other end of our difficulty:The problem Im hitting at the moment is that the very first lines in his AppDelegate.m (the class that actually begins the appthe very first thing thats run) has a reference call setting the oAuth2Session.clientID and .secretID for the BoxSDK sharedSDK property.  There is no sharedSDK property in the BoxContentClient and if I try to set it for the defaultClient for the BoxContentClient, it tells me that Im trying to assign a value to a read-only property.

    If there is any light you could shed on that specific issue, I believe we will be good to go.

    Translate