As Co-Admin, how to move folder in another user's account? - box-api

I am updating a user management script which we execute when someone leaves our company.
The app is aligned with a Co-Admin account and has all the various Enterprise scopes enabled (except for "Manage webhooks v2"). The "Read and write all files and folders stored in Box" scope is also checked.
Oh, am using the Python SDK.
Basically, the process works as follows:
First, we move the separating users '0' (top-level) folder to another account. This is kind of a custom function where we call /users//folders/0 via PUT with a JSON parameter of owned_by: <new_user_id>
Next we want to move that folder underneath a sub-folder of <new_user_id>. The code looks something like the following:
client.folder(folder_id=folder_to_move_id).as_user(new_user_id_obj_from_step_1).move(client.folder(folder_id=new_parent_folder_id))
However, this results in the following error:
boxsdk.exception.BoxAPIException:
Message: None
Status: 403
Code: None
Request id: None
Headers: {'Content-Length': '0', 'Age': '0', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains', 'Server': 'ATS', 'Connection': 'keep-alive', 'Date': 'Fri, 07 Apr 2017 22:52:43 GMT', 'WWW-Authenticate': 'Bearer realm="Service", error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."'}
URL: https://api.box.com/2.0/folders/23596411401
Method: PUT
Context info: None
Searching around for this "insufficient_scope" error, makes me think my access token needs to have requested some different scope, but (a) I'm not clear which one and (b) I'm not sure how to change scope mid-script. Maybe I should be approaching this a different way?
Thanks for any feedback.

Got the answer for this on the Box forums. Looks like we need to request that the GCM scope be enabled for our app and this must be done via Support.

Related

Facebook Graph API returns a different response on a different script but same -not invalid- tokens

I am trying to make a simple python script that posts a text message to a facebook page using requests.
I actually managed to succeed this feat, however, when I add the same logic to a bigger project of mine, a certain request returns a different json.
According to this page https://developers.facebook.com/docs/pages/access-tokens I can exchange the short lived user token I generate in the graph explorer tool for a long lived one that lasts 60 days. This worked for me until now. When I run the same functions, same variables on another .py file that includes other logic as well the request does not return this line:
"expires_in": SECONDS-UNTIL-TOKEN-EXPIRES
And of course later on if I continue the logic and use the token it returns (which is the same) for, let's say, a make_post function the request prints
{'error': {'message': '(#200) If posting to a group, requires app being installed in the group, and \\\n either publish_to_groups permission with user token, or both manage_pages \\\n and publish_pages permission with page token; If posting to a page, \\\n requires both manage_pages and publish_pages as an admin with \\\n sufficient administrative permission', 'type': 'OAuthException', 'code': 200, 'fbtrace_id': 'AqYMMeOcOniWAGgEEtsEURs'}
Why does it not successfully return, the user token had not expired and it has the requires rights. Furthermore I tested this in a smaller .py file and it worked.
Another thing I found out here https://developers.facebook.com/support/bugs/523165725596520/?join_id=f1ff8392b49675c here is that other people have actually reported the same issue but it has been closed as 'intended by design' however there is no information of a solution.
Running the request in my browser also does not work correctly.
Do you have any ideas? I am completely clueless.
Thank you very much in advance
As #CBroe in a comment said, the expires_in didn't have anything to do with my error. The token it returns if valid. The issue I had later on had to do with the url I was parsing

Vorto Dashboard not displaying the device model

while running the vorto dashboard im getting the following error
JWT expired, getting new Token Wed Aug 26 2020 07:38:56 GMT+0100 (BST)... StatusCodeError: 401 -
{"status":401,"error":"gateway:authentication.failed","message":"Multiple authentication
mechanisms were applicable but none succeeded.","description":"For a successful authentication
see the following suggestions: { The JSON Web Token is not valid. },
{ Please provide a valid JWT in the authorization header prefixed with 'Bearer ' }."
The contents of config.json is as follows
{
"client_id": "xxxxxxxxxxx",
"client_secret": "xxxxxxxxxxxx",
"scope": "xxxxxxxxxx",
"intervalMS": 10000
}
Tried with setting the contents of config.json as environment variables. Then also im getting same error. Screenshot of web front end on accessing localhost:8080 is attached
Tried with the following links Error running Vorto Dashboard for Bosch iot suite. But still its not working. Please help me in solving this issue
I have discussed the matter internally to Bosch (disclaimer: I am an employee).
After discussing with the Bosch Suite Auth team, here is a summary of what happened.
The Suite Auth team recently transitioned from Keycloack to Hydra for their authentication technology
The relevant bit here is that previously, the scopes passed to the token request were ignored
The Vorto Dashboard app had been passing the wrong key for the scope parameter all along, when requesting a token, but it was ignored
Now that this parameter is relevant, the (incorrect) notation was not failing to produce a token, but obtained one that was not suitable to authorize with Bosch IoT Things, because it did not contain the appropriate scope
In turn, fixing this key produces a token that successfully authorizes with Bosch IoT Things
If you're in a hurry, you can check out this branch with the fix (it's literally an 8 characters change set).
Otherwise, you can monitor this GitHub ticket for closure - I will close it when the fix is merged to the master branch of the Vorto Examples project.

VimeoUpload not re-authenticating After Deletion of App Access on Vimeo.com

I was able to connect and upload videos using the library but when I deleted the app connection on Vimeo.com (as a test) the app didn't authorize again.
the upload looks like it's working but nothing is uploaded as the app is no longer connected.
I deleted the app on the phone and restarted but it still won't re-authorize the app.
This comes up in the output:
Vimeo upload state : Executing
Vimeo upload state : Finished
Invalid http status code for download task.
And this is in OldVimeoUpload.swift: ( didn't include the actual access code!)
import Foundation
class OldVimeoUpload: VimeoUpload
{
static var VIMEO_ACCESS_TOKEN :String! // = "there's a string of numbers here"
static let sharedInstance = OldVimeoUpload(backgroundSessionIdentifier: "") { () -> String? in
return VIMEO_ACCESS_TOKEN // See README for details on how to obtain and OAuth token
}
// MARK: - Initialization
override init(backgroundSessionIdentifier: String, authTokenBlock: AuthTokenBlock)
{
super.init(backgroundSessionIdentifier: backgroundSessionIdentifier, authTokenBlock: authTokenBlock)
}
}
It looks like the access token number is commented out. I deleted the 2 forward slashes to see if that would fix it but it didn't.
I spoke too soon.
It sounds like you went to developer.vimeo.com and created an auth token. Used it to upload videos. And then went back to developer.vimeo.com and deleted the auth token.
The app / VimeoUpload will not automatically re-authenticated in this situation. You've killed the token and the app cannot request a new one for you. You'll need to create a new auth token and plug it into the app.
If this is not accurate and you're describing a different issue let us know.
If you inspect the error that's thrown from the failing request I'm guessing you'll see it's a 401 unauthorized related to using an invalid token.
Edit:
Disconnecting your app (as described in your comment below) has the same effect as deleting your auth token from developer.vimeo.com.
Also, VimeoUpload accepts a hardcoded auth token (as you see from the README and your code sample). It will not automatically re-authenticate, probably ever.
If you'd like to handle authentication in your app check out VimeoNetworking or VIMNetworking. Either of those libraries can be used to create a variety of authentication flows / scenarios. Still, if a logged in user disconnects or deletes their token, you will need them to deliberately re-authenticate (i.e. you will need to build that flow yourself). In that case, the user has explicitly stated that they don't want the app to be able to access information on their behalf. It would go against our security contract with them to automatically re-authenticate somehow.
Does that make sense?

Google Drive/OAuth - Can't figure out how to get re-usable GoogleCredentials

I've successfully installed and run the Google Drive Quick Start application called DriveCommandLine. I've also adapted it a little to GET file info for one of the files in my Drive account.
What I would like to do now is save the credentials somehow and re-use them without the user having to visit a web page each time to get an authorization code. I have checked out this page with instructions to Retrieve and Use OAuth 2.0 credentials. In order to use the example class (MyClass), I have modified the line in DriveCommandLine where the Credential object is instantiated:
Credential credential = MyClass.getCredentials(code, "");
This results in the following exception being thrown:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
at com.google.api.client.json.jackson.JacksonFactory.createJsonParser(JacksonFactory.java:84)
at com.google.api.client.json.JsonFactory.fromInputStream(JsonFactory.java:247)
at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.load(GoogleClientSecrets.java:168)
at googledrive.MyClass.getFlow(MyClass.java:145)
at googledrive.MyClass.exchangeCode(MyClass.java:166)
at googledrive.MyClass.getCredentials(MyClass.java:239)
at googledrive.DriveCommandLine.<init>(DriveCommandLine.java:56)
at googledrive.DriveCommandLine.main(DriveCommandLine.java:115)
I've been looking at these APIs (Google Drive and OAuth) for 2 days now and have made very little progress. I'd really appreciate some help with the above error and the problem of getting persistent credentials in general.
This whole structure seems unnecessarily complicated to me. Anybody care to explain why I can't just create a simple Credential object by passing in my Google username and password?
Thanks,
Brian O Carroll, Dublin, Ireland
* Update *
Ok, I've just gotten around the above error and now I have a new one.
The way I got around the first problem was by modifying MyClass.getFlow(). Instead of creating a GoogleClientServices object from a json file, I have used a different version of GoogleAuthorizationCodeFlow.Builder that allows you to enter the client ID and client secret directly as Strings:
flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, "<MY CLIENT ID>", "<MY CLIENT SECRET>", SCOPES).setAccessType("offline").setApprovalPrompt("force").build();
The problem I have now is that I get the following error when I try to use flow (GoogleAuthorizationCodeFlow object) to exchange the authorization code for the Credentials object:
An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "invalid_scope"
}
googledrive.MyClass$CodeExchangeException
at googledrive.MyClass.exchangeCode(MyClass.java:185)
at googledrive.MyClass.getCredentials(MyClass.java:262)
at googledrive.DriveCommandLine.<init>(DriveCommandLine.java:56)
at googledrive.DriveCommandLine.main(DriveCommandLine.java:115)
Is there some other scope I should be using for this? I am currently using the array of scopes provided with MyClass:
private static final List<String> SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile");
Thanks!
I feel your pain. I'm two months in and still getting surprised.
Some of my learnings...
When you request user permissions, specify "offline=true". This will ("sometimes" sic) return a refreshtoken, which is as good as a password with restricted permissions. You can store this and reuse it at any time (until the user revokes it) to fetch an access token.
My feeling is that the Google SDKs are more of a hinderence than a help. One by one, I've stopped using them and now call the REST API directly.
On your last point, you can (just) use the Google clientlogin protocol to access the previous generation of APIs. However this is totally deprecated and will shortly be turned off. OAuth is designed to give fine grained control of authorisation which is intrinsically complex. So although I agree it's complicated, I don't think it's unnecessarily so. We live in a complicated world :-)
Your and mine experiences show that the development community is still in need of a consolidated document and recipes to get this stuff into our rear-view mirrors so we can focus on the task at hand.
Oath2Scopes is imported as follows:
import com.google.api.services.oauth2.Oauth2Scopes;
You need to have the jar file 'google-api-services-oauth2-v2-rev15-1.8.0-beta.jar' in your class path to access that package. It can be downloaded here.
No, I don't know how to get Credentials without having to visit the authorization URL at least once and copy the code. I've modified MyClass to store and retrieve credentials from a database (in my case, it's a simple table that contains userid, accesstoken and refreshtoken). This way I only have to get the authorization code once and once I get the access/refresh tokens, I can reuse them to make a GoogleCredential object. Here's how Imake the GoogleCredential object:
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
.setTransport(httpTransport).setClientSecrets(clientid, clientsecret).build();
credential.setAccessToken(accessToken);
credential.setRefreshToken(refreshToken);
Just enter your clientid, clientsecret, accessToken and refreshToken above.
I don't really have a whole lot of time to separate and tidy up my entire code to post it up here but if you're still having problems, let me know and I'll see what I can do. Although, you are effectively asking a blind man for directions. My understanding of this whole system is very sketchy!
Cheers,
Brian
Ok, I've finally solved the second problem above and I'm finally getting a working GoogleCredential object with an access token and a refresh token.
I kept trying to solve the scopes problem by modifying the list of scopes in MyClass (the one that manages credentials). In the end I needed to adjust the scopes in my modified version of DriveCommandLine (the one that's originally used to get an authorization code). I added 2 scopes from Oauth2Scopes:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE, Oauth2Scopes.USERINFO_EMAIL, Oauth2Scopes.USERINFO_PROFILE))
.setAccessType("offline").setApprovalPrompt("force").build();
Adding the scopes for user information allowed me to get the userid later in MyClass. I can now use the userid to store the credentials in a database for re-use (without having to get the user to go to a URL each time). I also set the access type to "offline" as suggested by pinoyyid.

How to authenticate with Chrome sync XMPP servers?

I need to get the currently opened tabs of a Google Chrome user in my Java application (not on the same machine). Chrome sync is enabled so the current tabs are synced with Google servers.
According to the documentation of Chrome sync it is done via XMPP. So I guess it should be possible to connect to the Google XMPP server (xmpp.google.com), e.g. via Smack (Java library for XMPP), authenticate and listen for protobuf messages that indicate a tab session change.
Of course the login credentials of the user or the "client_id" Chrome uses to identify clients are available.
But I'm having a hard time getting behind the authentication method that is used to connect to the XMPP server – I can't figure out how it's done in the Chromium source code and there's no documentation available besides the very low-level comments in the code.
The libjingle library Google uses for it's XMPP based services is only available for C++ and not well maintained/documented.
So is there anyone who has done something like that before and who can give any advice/hints on how the authentication process works?
I'm not sure chrome sync uses xmpp, at least on the level when it has to exchange info with client. It uses 'protocol buffers' Google technology. The protocol is given by using .proto protocol description files and you can convert it to your language's objects by using special compiler.
The sync server seems to rest at https://clients4.google.com/chrome-sync and client sends POST requests with the binary body where typed ClientToServerMessage message is placed.
Here's the output from when first connecting to sync server.
The first output Python object is a pprint of 'environ' WSGI variable where HTTP headers are placed too. The second object (after '====' ) is actual protocol message.
{'CONTENT_LENGTH': '54',
'CONTENT_TYPE': 'application/octet-stream',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
'HTTP_AUTHORIZATION': 'GoogleLogin auth=MKhiqZsdz2RV4WrUJzPltxc2smTMcRnlfPALTOpf-Xdy9vsp6yUpS5cGuND0awqrYVUK4lhOJlh6OMsg093eBRghGGIgvWUTzU8PUvquy_c8Xn4sRiz_3tVJcke5eXi3q4qFDa6iVuEbT_0QhyPOjIQyeDOKRpZzMR3rpHsAs0ptFiTtUeTHsoIeUFT9nZPYzkET4-yHbDAp45_dxWdb-U6DPg24',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_HOST': 'localhost:8080',
'HTTP_USER_AGENT': 'Chrome MAC 0.4.21.6 (130497)-devel',
'PATH_INFO': '/chrome-sync/dev/command/',
'QUERY_STRING': 'client_id=SOME_SPECIAL_STRING',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': '59031',
'REQUEST_METHOD': 'POST',
'SCRIPT_NAME': '',
'SERVER_NAME': 'vian-bizon.local',
'SERVER_PORT': '8080',
'SERVER_PROTOCOL': 'HTTP/1.0',
'SERVER_SOFTWARE': 'gevent/1.0 Python/2.6',
'wsgi.errors': <open file '<stderr>', mode 'w' at 0x100416140>,
'wsgi.input': <gevent.pywsgi.Input object at 0x102a04250>,
'wsgi.multiprocess': False,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.url_scheme': 'https',
'wsgi.version': (1, 0)}
'==================================='
share: "MY_EMAIL_WAS_HERE#gmail.com"
protocol_version: 30
message_contents: GET_UPDATES
get_updates {
caller_info {
source: NEW_CLIENT
notifications_enabled: false
}
fetch_folders: true
from_progress_marker {
data_type_id: 47745
token: ""
notification_hint: ""
}
}
debug_info {
events {
type: INITIALIZATION_COMPLETE
}
events_dropped: false
}
This happens for OAuth based authentication. You can see the OAuth token in HTTP_AUTHORIZATION field. The OAuth token is given to you when you interact with HTML dialog 'Google Account Login'. I'm not sure but seems like the API to get an access token for Google services is available publicly.
If you are looking for XMPP auth instead, please see the description of X-GOOGLE-TOKEN auth mechanism here:
Authenticate to Google Talk (XMPP, Smack) using an authToken
For the X-OAUTH2 authorization, you can access the info here: https://developers.google.com/talk/jep_extensions/oauth
And a sample here: http://pits.googlecode.com/svn/trunk/xmpp.c
Note that you can add XMPP stream flow to the Chrome log files populated on each run of the browser - chrome_debug.log. To enable this, run Chrome with following options: --enable-logging --v=2