How To Add A User Alias Using Google Admin SDK Java API - java

I am using the service account model and Google's Admin SDK Java API to retrieve and modify users.
The goal is to add an alias for an existing user.
Alias newAlias = new Alias();
newAlias.setId(userID);
newAlias.setAlias(alias);
Directory.Users.Aliases.Insert request = directory.users().aliases().insert(userID, newAlias);
request.execute();
execute() fails 100% of the time with the error message:
"Value set through a parameter is inconsistent with a value set in the request"
but of course does not identify the problem parameter or value, or provide a suggestion.
I tried all 8 combinations of scoped (or not scoped) userID and alias in newAlias, and userID in the request, with the same result. By all 8 combinations, I mean:
newAlias.setId(userID);
newAlias.setAlias(alias);
insert(userID, newAlias);
newAlias.setId(userID#domain.com);
newAlias.setAlias(alias#domain.com);
insert(userID#domain.com, newAlias);
and so on...
Any ideas greatly appreciated.

I think it is worth adding that, while I believe the above approach is correct (using Directory.Aliases.Insert) and that I am missing some critical information or made a mistake, I also attempted to add the alias by updating the User object instead of Aliases, something like this:
List<String> aliases = new ArrayList<String>();
aliases.add(scopedAlias); //userid#domain.com
User user = new User();
user = retrieveUser(uid); //Gets current record from Google
user.setAliases(aliases);
Directory.Users.Update request
= directory.users().update(uid, user);
request.execute();
That did not work either.
Anyone have an example of working code?

I've gotten aliases inserted using the following:
Alias alias = new Alias();
alias.setAlias(aliasString);
directory.users().aliases().insert(userId, alias).execute();
I don't have anything in the way of insight as to why your approach isn't working or why my approach works, but there you go.

S. McKinley's suggestion worked.
The key difference:
I had been including the call:
alias.setId(userId);
or
alias.setId(scopedUserId); //userId#domain
Either one resulted in the "parameter is inconsistent with a value" error. Leave it out and the alias gets created.

I was able to find the customerId as follows
Go to admin.google.com
Security -> Set up single sign-on (SSO)
You will see URLs like this:
https://accounts.google.com/o/saml2/idp?idpid=Cxxxxxxxx
That Cxxxxxxxx is your customerId

Related

How to list all root folder and shares on the Google Drive API v3 while paging and using order by?

I've seen a few questions about this but none cover my scenario.
Basically what I want is to use tokens to do paging and also list all folders and files in the root folder including shared files and folders.
This appears to be working, but once I add orderBy it doesn't work well. It works ok with sorting if I remove or sharedWithMe = true but once I add it it like the shared items aren't sorted.
What am I doing wrong?
This is my code (Kotlin and on Android):
val response =
gDriveClient.files()
.list()
.setSpaces("drive")
.setCorpora("user")
.setFields("files(id, name, size, modifiedTime, mimeType, parents, quotaBytesUsed),nextPageToken")
.setQ("('root' in parents or sharedWithMe = true) and trashed = false")
.setOrderBy("folder,name")
.setPageSize(params.loadSize)
.setPageToken(token)
Unfortunately, the behaviour you are experiencing seems to be a bug as your query and request is formatted correctly and necessary to obtain exactly what you were looking for. I have reported this behaviour here : https://issuetracker.google.com/issues/174476354 . Please consider starring the report to indicate that this is also affecting you.
Workaround
A possible workaround to this would be to order and filter your response after the request has been executed which unfortunately will not let you perform the request with pagination for your specific purpose (as for ordering everything you would need all the files).
References
Drive.Files.list()
Query parameter sharedWithMe

box-api search parameters not working?

I'm using the Java SDK to connect to Box. I find the root folder (this is a small dev instance so I don't mind searching from there.) I execute the search query and I get results. My problem is that the search parameters do not seem to work consistently or at all.
For example, this query
Iterator resultSet = rootFolder.search("query=NR_chewy_chic_swt_pot_app&file_extensions=jpg&content_type=name&type=file").iterator();
returns three entries.
NR_chewy_chic_swt_pot_app.jpg
NR Chewy Chicken AD02.xls
PreInvoice_M197301-3644756_NR Chewy Treats SURP.pdf
I remove the substring "&file_extensions=jpg" because it doesn't seem to do anything and save/recompile/run and I get the same three results.
I change "&type=file" to "&type=folder" and I get the same three results.
I change "query=NR_chewy_chic_swt_pot_app" to "query=NR" and I get NO results. Even though SO user Peter (who appears to work for Box) says that partial strings should match1.
I've tried rearranging the order of the search parameters to no avail. What am I missing?
Thanks,
Eric B.
Advanced search has yet to be implemented in the SDK (since it's still in beta), but it will be added in the coming weeks.
The reason why your call doesn't work is because the query method parameter is sent as the "query" URL parameter in the API call. Therefore, the ampersands in your query string are being escaped.
If you need an immediate workaround, you can use the BoxAPIRequest and BoxAPIResponse classes to make a custom search request. For example:
BoxAPIConnection api = new BoxAPIConnection("token");
URL url = new URL("https://api.box.com/2.0/search?query=NR_chewy_chic_swt_pot_app&file_extensions=jpg&content_type=name&type=file")
BoxAPIRequest request = new BoxAPIRequest(api, url, "GET");
BoxJSONResponse response = (BoxJSONResponse) request.send();
String json = response.getJSON();
Sorry that this wasn't clear. We'll update the documentation to make it more explicit that query represents the query field and not the URL query string.

Google Cloud Storage setting permissions gives bad request errors Java JSON API

I'm using the JSON API Java library to upload objects to Google Cloud Storage. I've figured out how to add the entity allUsers with role READER to get public access, but any other entity/role entries I try to add to my list of ObjectAccessControl produce some generic errors like
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Value",
"reason" : "invalid"
}
...for each ACL entry I have, except the allUsers READER one which seems to work
I'm not sure what it's complaining about here. I'm trying to reproduce the default permissions I see in the Developers Console, i.e. when I don't specify any ACL on the metadata.
owners-projectId owner,
editors-projectId owner,
viewers-projectId reader,
and user Id owner (I am guessing this is the service account ID)
I'm adding these to the ACL list the same way as the allUsers entity. I've searched for hours trying to find some documentation or similar issues to this, but only found the one regarding allUsers. I've tried escaping these ids, thinking the JSON library might not be doing so for me, but get the same errors.
Here's my relevant Java code:
// Set permissions and content type on StorageObject metadata
StorageObject objectMetadata = new StorageObject();
// set access control
List<ObjectAccessControl> acl = Lists.newArrayList();
acl.add(new ObjectAccessControl().setEntity("allUsers").setRole("READER"));
// this one allows upload to work without error if it is the only access specified,
// but prevents me from modifying publicly available status or editing permissions
// via the developers console (I think this is to be expected)
// attempt to replicating bucket defaults...
// adding any of these will cause the error
acl.add(new ObjectAccessControl().setEntity("owners-projectId").setRole("OWNER"));
acl.add(new ObjectAccessControl().setEntityId("editors-projectId").setRole("OWNER"));
acl.add(new ObjectAccessControl().setEntityId("viewers-projectId").setRole("READER"));
objectMetadata.setAcl(acl);
where projectId is my project ID copied from the Developer's console site.
Finally figured this out.
I first suspected my storage scope of DEVSTORAGE_READ_WRITE was not sufficient, and tried DEVSTORAGE_FULL_CONTROL, but that was not the reason.
Also ignore my use of setEntityId(...) in my original post, although this was something I also tried to no avail.
The problem was simply incorrect syntax in the entity argument. The document you need is this:
https://cloud.google.com/storage/docs/json_api/v1/defaultObjectAccessControls
Then you will see that the proper method looks something like:
acl.add(new ObjectAccessControl().setEntity("project-owners-projectId").setRole("OWNER"));
Oddly enough, this did NOT work:
acl.add(new ObjectAccessControl().setProjectTeam(new ProjectTeam().setProjectNumber("projectId").setTeam("owners")).setRole("OWNER"));
I suspect that method of setting the project team entity is a bug in the Java library, but I'm not sure.
The error message for incorrect entities that keeps saying Domain global required, or Domain global invalid value, is simply not very instructive. Setting domain is not required for this case. Also see the discussion at:
What domain is Google Cloud Storage expecting in the ACL definitions when inserting an object?
Hope this helps someone else out!
You can set the access control permission by using "predefinedAcl" the code is as follows.
Storage.Objects.Insert insertObject =client.objects().insert(, ,);
insertObject.setPredefinedAcl("publicRead");
This will work fine

CreateUser in DefaultUserAccessor

Can someone please explain what is the difference between CreateUser(String) and CreateUser(User,Credential) in confluence. I want to create one user for confluence, if user is not there in the group. There is no information in confluence documentation. :(
I wrote code like this, but not sure whetehr it will accept createUser method twice in same line.
userAccessor.createUser(userAccessor.createUser(username), Credential.encrypted(password));
I am guesing, if inside createUser is executed,then it will throw an exception at outside parent createUser as it is trying to create same user again?
Please give me your thoughts
Thanks
Samuel.
The new createUser(User, Credential) method replaces the old createUser(String) method, so you should use the former and construct a user with all the details:
User user = userAccessor.createUser(new DefaultUser("mryall", "Matt Ryall", "matt#mattryall.net"),
Credential.unencrypted("secret"));
The reason for having this API was to reduce the number of calls needed to create a user, and fix the potential race condition where you're creating a user with a username but with otherwise empty fields (name, email, password).
This entire API is very poorly documented. I work on the Confluence team at Atlassian - so mea culpa! We'll try to get this fixed.

Java EE : Prevent application URL hacking

I am working on an existing Web based application.
Now, I need to secure the application against what I think is called url hacking. For instance, if the customer with customerId 1 is logged in and viewing his profile, the following http get variable will be visible in the address field: customerId=1.
I need to prevent a customer from being able to set customerId=2 and see the profile of another customer.
The problem is that, the application is already in production and in good working condition, so the changes should be minimal with respect to this change.
How is this best achieved?
Any sugggestions/comments?
why do you give the id in the URL when the user should only be allowed to change his profile? I don't see any need for this. Rather get the current user from SecurityConext and display its profile on an URL without the id.
with the new information you gave in the comments I suggest sth. like this:
just check if the given orderid in the URL belongs to the current user.
You're saying you use "normal web based Application" so I assume Servlet/jsp based. In your servlet you would do something like this:
int orderId = Integer.parseInt(request.getParameter("orderId"));
String username = request.getUserPrincipal().getName();
/*now you need to check if username match with the username of the order e.g. by using hibernate to get the order by id and check its user and if not throw PermissionDeniedException or similiar*/
95% agree with Korgen's answer above.
5% - if you want to allow administrator access to edit user profiles using the same functionality just switch to UUID to identify edited user.

Categories

Resources