node.js SDK - basic authentication questions
I'm fairly new to node.js, and very new to OAuth2, so my apologies if this is unbelievably basic...
I'm trying to make sense of the node.js authentication documentation, and I'm getting hung up on a couple of things.
- In the example for normal authentication is this line:
var TokenStore = require('TOKEN-STORE-IMPLEMENTATION');
What "TOKEN-STORE-IMPLEMENTATION" is recommended? What are the possibilities? What are the requirements for a token store implementation? How would I find a compatible token store implementation?
- In the same section is this line:
sdk.getTokensAuthorizationCodeGrant('YOUR-AUTH-CODE', null, function(err, tokenInfo) {
What is "YOUR-AUTH-CODE"? Is that something configured on my Box application that I need to make sure matches between my code and the configuration? Is that something dynamically generaged (and if so, what should I do with it)?
Thanks very much!
-
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.
-
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 + '!');});
-
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?
-
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.
-
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.
-
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?
-
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.
-
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. )
-
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
-
Hi guys,
I now have my Box app authenticating properly. There were three things I was not appreciating,
- I needed to have my Box app configured to Application access: Enterprise
- I needed to re-authorise my app when I made any changes to it
- 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.
Please sign in to leave a comment.
Comments
13 comments