node.js SDK - basic authentication questions

New post

Comments

13 comments

  • scottsm777

    Note: I did find the example implementation of token store, so that answers part of question 1 (what are the requirements of a token store implementation), but it doesn't answer what production-ready token store implementations are out there.

    0
    Comment actions Permalink
  • SalsaShark42

    This isn't particularly pretty, or complete, code, but it might give you somewhere to start.  This is a simple example where the access and refresh tokens are stored in a JSON file (this is for a single server-side batch process. I primarily program in Python, so I have a standalone utility that handles the initial Box authorization and generates the tokens.  It normally puts them directly into Windows Credential Manager, but, for JavaScript, I'll just copy-and-paste into the JSON file.  Unfortunately, I don't currently have any JavaScript that helps with the first-time token generation, but I'll be happy to share the Python code if you can use that instead.

     

    For the sample below, you'll need an existing "boxTokens.json" file that looks like this:

     

    {"accessToken":"blahblahblah","refreshToken":"blahblahblah"}

     

    "blahblahblah" represents the access and refresh tokens you'll get from that first-time authorization process.  After you run the JavaScript, below, your JSON file will look like this:

     

    {"accessToken":"UPDATED_ACCESS_TOKEN","refreshToken":"UPDATED_REFRESH_TOKEN","accessTokenTTLMS":3893000,"acquiredAtMS":removed for privacy1402}

     

    var boxSDK = require('box-node-sdk');
    var jsonfile = require('jsonfile');
    var file = './boxTokens.json';

     

    tokensFile = jsonfile.readFileSync(file);

    var sdk = new boxSDK({
        clientID: 'YOUR_CLIENT_ID',
        clientSecret: 'YOUR_CLIENT_SECRET'
    });

     

    sdk.getTokensRefreshGrant(tokensFile.refreshToken, function(err, tokenInfo) {
        if (err) {
            throw err;
        }

        tokenString = JSON.stringify(tokenInfo);

        jsonfile.writeFileSync(file, tokenInfo);

        boxClient = sdk.getPersistentClient(tokenInfo);
        boxClient.users.get(boxClient.CURRENT_USER_ID, null, function(err, currentUser) {
            if(err) {
                console.log('Error!!!');
            }
        console.log('Hello, ' + currentUser.name + '!');

    });

    0
    Comment actions Permalink
  • scottsm

    Thanks, SalsaShark42, but I've tried various permutations of your code in my app, and I get "Error: Expired Auth: Auth code or refresh token has expired." on the call to sdk.getTokensRefreshGrant(). I've tried using the sdk.getTokensAuthorizationCodeGrant() method as described in the SDK documentation and I get the same error there.

     

    Any more suggestions?

    0
    Comment actions Permalink
  • scottsm

    Hmmmm -- I took a closer look at the docs and I saw this in the section about PersistentClient:

     

     

     

    After a user logs in and grants your application access to their Box account,
    they will be redirected to your application's `redirect_uri` which will contain
    an auth code. This auth code can then be used along with your client ID and
    client secret to establish an API connection.  A `PersistentClient` will
    automatically refresh the access token as needed.

    Key phrase: "after a user logs in".

     

    So my question is probably even more basic: What do I do in my web app to get the user to sign in to Box so that my callback can be invoked? The Box documentation seems to assume that I know how to do that...or maybe I haven't found the "box integration for complete beginners" page.

     

     

    0
    Comment actions Permalink
  • scottsm

    Okay, I found the page I was looking for: https://docs.box.com/docs/oauth-20

    Not sure why I was having trouble finding that...

    But since this is part of the overall API documentation, it's not clear how much of all of that I need to do vs how much the SDK does for me....

    Still struggling but making progress.

    0
    Comment actions Permalink
  • SalsaShark42

    As I mentioned in my original post, I have a Python utility that establishes that initial authorization (and, thus, generates the first access and refresh tokens).  Part of that process involves the utility launching a browser window to Box and prompting the user to log in and authorize the application to access that Box instance.

     

    And it's not necessarily a problem if you see a message about the token being expired.  If you're using one of the Box SDKs, it will handle that error and try to refresh the token/get a new, valid one.

     

    So I guess the first question is this:  Have you completed that initial authorization/token generation process?

    0
    Comment actions Permalink
  • Box Product Support

    Hi scottsm, are you able to go throught the whole auth procee once? 

     

    I feel the document are in difference places and lots of unexplain term. I read all documents I can find online but still can't figure out why. Can you share your code or thought if possible?

     

    Thanks!

     

    0
    Comment actions Permalink
  • SalsaShark42

    Where are you stuck?  The sample code I posted provides an example of how to handle the authentication/tokens after you've done the initial user authorization.  You can do that first-time authorization using something like Postman or I can post some sample Python code that will facilitate it.

     

    It would help if you could be specific on where you're stuck.

    0
    Comment actions Permalink
  • matt-lindsay

    Hi guys, have you made any progress with this?

     

    I'm getting 'The authorization code has expired' after implementing the example token store. Any help you could offer would be greatly apprciated thanks.

    0
    Comment actions Permalink
  • edwardqi

    I think the detail doc here will be helpful oauth-20, at least it's working fine for me to get the refresh/access token at first time, then use the refresh token to generate new access token. (note:the authorization code will expire in 30 seconds after generation. )

    0
    Comment actions Permalink
  • cameron-porter

    Hello all, 

     

    I am currently having difficulties with the authentication process. Hopefully, you guys can help! 

     

    I am using the `box-node-sdk` and am trying to use authentication with JWT as specified here https://developer.box.com/v2.0/docs/authentication-with-jwt.

     

    I have successfully created an app user using the service client, however, when I try to access the content API as that user I get the following error:

     

    Error: Expired Auth: Auth code or refresh token has expired.

    I can not figure out how to get the app users refresh token and I don't have an auth code because I used JWT authentication which skips the first leg of the three-legged OAuth2 protocol. 

     

    What follows is the code that led to the error.

     

    First I read in the box configuration that I downloaded from the developer console and use that create a preconfigured instance of the SDK.

     

    // configure service account client
    const sdk = BoxSDK.getPreconfiguredInstance(boxConfig)
    const serviceClient = sdk.getAppAuthClient('enterprise')

    I then ensure that this service client is properly configured by fetching `me`. 

     

    // Ensure that service account is working and fetch service account user
    serviceClient.users.get('me', null)
      .then((serviceAccountUser) => {
        console.log(serviceAccountUser)
      })
      .catch((err) => {
        console.log(err)
      })

    This returns the app user I had created previously.  I then use that user id `USER_ID` to create a user client.

     

    // create user client
    const userClient = sdk.getAppAuthClient('user', USER_ID)

    Next, I attempt to use that user client to access the content API. 

     

    // access content API
    userClient.folders.getItems('0', null) 
      .then((data) => {
        console.log(data)
      })
      .catch((err) => {
        console.log(err)
      })

    This returns the following error.

     

    Error: Expired Auth: Auth code or refresh token has expired.

     

    I hope that that is a clear explanation of the issue I am having. If you know what is the best way for me to access the refresh token, that would be much appreciated.

     

    Thanks!

    Cam

    0
    Comment actions Permalink
  • matt-lindsay

    Hi Cam, I have a remote session with Box regarding this on Thursday. I'll update the thread if I get it resolved.

    Matt.

    0
    Comment actions Permalink
  • matt-lindsay

    Hi guys,

     

    I now have my Box app authenticating properly. There were three things I was not appreciating,

    1. I needed to have my Box app configured to Application access: Enterprise
    2. I needed to re-authorise my app when I made any changes to it
    3. I was not impersonating a managed user

    I have a working example on GitHub and a blog post with more detail here

     

    I hope you find it useful.

    Matt.

    0
    Comment actions Permalink

Please sign in to leave a comment.