Getting all ActiveDirectory groups using OpenSSO Client SDK - java

I hope someone here has experience with Sun OpenSSO (now ForgeRock OpenAM).
I'm trying to get all groups in ActiveDirectory using the OpenSSO Client SDK in Java / JBoss EAP 5.0.
I tried the following by combining various samples and code snippets I could find on the web, but this fails and eventually logs "Memberships for identities other than Users is not allowed." The basic approach was to use AMIdentityRepository -> getRealmIdentity() -> getMemberships(IdType.GROUP) :
SSOTokenManager manager = SSOTokenManager.getInstance();
String tokenString = URLDecoder.decode(tokenID, "ISO-8859-1");
SSOToken token = manager.createSSOToken(tokenString);
if (manager.isValidToken(token)) {
SSOToken adminToken = (SSOToken)AccessController.
doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository rep = new AMIdentityRepository(adminToken, "/");
AMIdentity identity = rep.getRealmIdentity();
Set groups = identity.getMemberships(IdType.GROUP);
}
Note I'm not trying to determine if a user is a member of a group or to retrieve a user's groups - I'm trying to get a list of ALL groups.
Any suggestions would be appreciated - thanks!

Instead of rep.getRealmIdentity() and then calling getMemberships(IdType.GROUP), use searchIdentities and getSearchResults like:
SSOToken token = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
AMIdentityRepository ir = new AMIdentityRepository(token, "/");
IdSearchResults results = ir.searchIdentities(IdType.GROUP, "*", new IdSearchControl());
Set<AMIdentity> groups = results.getSearchResults();
for (AMIdentity group : groups) {
logger.debug("Group Name : " + group.getName());
}

Related

Add AWS SQS Permission to all Principals through SDK

I'm trying to create an AWS SQS queue through the Java SDK, and then add all permissions for all users. I can create the queue fine, but I'm struggling to know what value I can pass in for the Principals. This is what my code looks like:
CreateQueueRequest createQueueRequest = new CreateQueueRequest(queueName).withAttributes(attributes);
CreateQueueResult createQueueResult = amazonSqs.createQueue(createQueueRequest);
String queueUrl = createQueueResult.getQueueUrl();
amazonSqs.addPermission(queueUrl, "*", ????, Arrays.asList("*"));
The ??? is what I'm not sure on. I've tried Arrays.asList("*") but it complains about it not being valid. In the web console, there is a checkbox for Everyone, and I'm just wanting to do the same thing in the SDK. Is there some value I can pass for this?
--- UPDATE ---
I've been able to accomplish this another way through a Policy:
String queueUrl = createQueueResult.getQueueUrl();
GetQueueAttributesResult getQueueAttributesResult = amazonSqs.getQueueAttributes(queueUrl, Arrays.asList(QUEUE_ARN_ATTRIBUTE_NAME));
String queueArn = getQueueAttributesResult.getAttributes().get(QUEUE_ARN_ATTRIBUTE_NAME);
if (needToSetPolicy)
{
Policy allAccessPolicy = new Policy("SQSAllAccess", Arrays.asList(
new Statement(Effect.Allow)
.withActions(() -> "SQS:*")
.withPrincipals(Principal.All)
.withId("SQSAllAccessStatement")
.withResources(new Resource(queueArn))
));
Map<String, String> policyMap = new HashMap<>(1);
policyMap.put(POLICY_ATTRIBUTE_NAME, allAccessPolicy.toJson());
amazonSqs.setQueueAttributes(queueUrl, policyMap);
}
It seems like there should be a better/easier way to do this. Are there any better/cleaner/easier ways of doing this?
In kotlin using the constants from the SDK
val policy: Policy = Policy("AllowAllSendMessage", listOf(Statement(Effect.Allow)
.withActions(SQSActions.SendMessage)
.withPrincipals(Principal.All)
.withId("AllowAllSendMessage")
.withResources(Resource(queueArn))))
_sqs.setQueueAttributes(SetQueueAttributesRequest()
.withQueueUrl(queueUrl)
.withAttributes(mapOf(QueueAttributeName.Policy.toString() to policy.toJson())))

Bing ads Campaign Management

I have recently started playing with the Bing Ads api for managing my ads and campaigns and I am having problem in authenticating user (not oauth authentication).
I authenticated my user using oauth by the following
private String devToken = "ZZZZZ";
private String clientId = "AAA0BBB-XXXX-AAAAA";
protected static String UserName = "a.v#h.c";
protected static String Password = "********";
// To get the initial access and refresh tokens you must call requestAccessAndRefreshTokens with the authorization redirection URL.
OAuthTokens tokens = oAuthDesktopMobileAuthCodeGrant.requestAccessAndRefreshTokens(url);
System.out.println("Access token: " + tokens.getAccessToken());
System.out.println("Refresh token: " + tokens.getRefreshToken());
authorizationData = new AuthorizationData();
authorizationData.setDeveloperToken(getDevToken());
authorizationData.setAuthentication(oAuthDesktopMobileAuthCodeGrant);
This authenticates my user just fine since I can use the ICustomerManagementService.class just fine for accounts related information
customerServiceClient = new ServiceClient<>(authorizationData, ICustomerManagementService.class);
ArrayOfAccount accounts = searchAccountsByUserId(user.getId());
The above works perfectly. But when I try to do the same with ICampaignManagementService.class like below
campaignServiceClient = new ServiceClient<>(authorizationData, ICampaignManagementService.class);
GetAdsByAdGroupIdRequest cReq = new GetAdsByAdGroupIdRequest();
cReq.setAdGroupId(1234567890L);
campaignServiceClient.getService().getAdsByAdGroupId(cReq);
I get error code 106 saying that the user is not authorized.
The user does not represent a authorized developer.
106
Any help in this regard ?
Please try to set the CustomerId and CustomerAccountId header elements (CustomerId and AccountId of AuthorizationData). These headers are not available with the Customer Management service, but are applicable for Campaign Management service. If that does not resolve the issue please feel free to send the SOAP request + response to support for investigation. I hope this helps!

Finding product in category

I need to find products in different categories on eBay. But when I use the tutorial code
ebay.apis.eblbasecomponents.FindProductsRequestType request = new ebay.apis.eblbasecomponents.FindProductsRequestType();
request.setCategoryID("Art");
request.setQueryKeywords("furniture");
I get the following error: QueryKeywords, CategoryID and ProductID cannot be used together.
So how is this done?
EDIT: the tutorial code is here.
EDIT2: the link to the tutorial code died, apparently. I've continued to search and the category cannot be used with the keyword search, but there's a Domain that you could presumably add to the request, but sadly it's not in the API - so I'm not sure if indeed it can be done.
The less-than-great eBay API doc is here.
This is my full request:
Shopping service = new ebay.apis.eblbasecomponents.Shopping();
ShoppingInterface port = service.getShopping();
bp = (BindingProvider) port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
// Add the logging handler
List<Handler> handlerList = bp.getBinding().getHandlerChain();
if (handlerList == null) {
handlerList = new ArrayList<Handler>();
}
LoggingHandler loggingHandler = new LoggingHandler();
handlerList.add(loggingHandler);
bp.getBinding().setHandlerChain(handlerList);
Map<String,Object> requestProperties = bp.getRequestContext();
Map<String, List<String>> httpHeaders = new HashMap<String, List<String>>();
requestProperties.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
httpHeaders.put("X-EBAY-API-CALL-NAME", Collections.singletonList(CALLNAME));
httpHeaders.put("X-EBAY-API-APP-ID", Collections.singletonList(APPID));
httpHeaders.put("X-EBAY-API-VERSION", Collections.singletonList(VERSION));
requestProperties.put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders);
// initialize WS operation arguments here
FindProductsRequestType request = new FindProductsRequestType();
request.setAvailableItemsOnly(true);
request.setHideDuplicateItems(true);
request.setMaxEntries(2);
request.setPageNumber(1);
request.setQueryKeywords("Postcard");
request.setDomain("");
The last line, which should set the domain like I need to, does not compile. Any idea how to solve this?
EDIT 3: I gave up on the Java API and I'm doing direct REST. The categories on eBay are actually domains now, and the URL looks like this:
String findProducts = "http://open.api.ebay.com/shopping?callname=FindProducts&responseencoding=XML&appid=" + APPID
+ "&siteid=0&version=525&"
+ "&AvailableItemsOnly=true"
+ "&QueryKeywords=" + keywords
+ "&MaxEntries=10"
+ "&DomainName=" + domainName;
This works, but you want to hear a joke? It seems like not all the domains are listed here and so it doesn't really solve this problem. Pretty disappointing work by eBay.
The solution for finding items based on keywords, in a category, is to use findItemsAdvanced. Could have saved me a lot of time if the docs for FindProducts stated this, instead of just saying that you can use either keyword search OR category search.
This is the API URL:
http://open.api.ebay.com/shoppingcallname=findItemsAdvanced&responseencoding=XML&appid=" + APPID
+ "&siteid=0&version=525&"
+ "&AvailableItemsOnly=true"
+ "&QueryKeywords=" + keywords
+ "&categoryId=" + categoryId
+ "&MaxEntries=50
For completion, if you want to get a list of all the top categories you can use this:
http://open.api.ebay.com/Shopping?callname=GetCategoryInfo&appid=" + APPID + "&siteid=0&CategoryID=-1&version=729&IncludeSelector=ChildCategories

DirContext : Active Directory Ldap request: get groups of user with parent groups

I use javax.naming.directory.DirContext to create a LDAP request for Active Directory. This request returns groups of which the user with given name is member of.
hSearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setCountLimit(1);
searchCtls.setReturningAttributes(new String[]{"memberOf"});
String searchFilter = MessageFormat.format("(sAMAccountName={0})", new Object[]{userName});
NamingEnumeration answer = null;
try {
String hostDC = host.replaceAll("\\.", ",dc=");
adSearchRequestCr = adSearchRequestCr.replace("DL3", getDomainName(host, 3));
adSearchRequestCr = adSearchRequestCr.replace("DL2", getDomainName(host, 2));
adSearchRequestCr = adSearchRequestCr.replace("DL1", getDomainName(host, 1));
answer = context.search(adSearchRequestCr, searchFilter, searchCtls);
}
This works fine but now I need to change this request. Changed request should return not just group in which the user is, but also parent groups of that group and so on (tree of groups). I read about LDAP_MATCHING_RULE_IN_CHAIN, but I still didn`t manage to use it.
Please help with using LDAP_MATCHING_RULE_IN_CHAIN or smth similar to get new aim of the request.
Finally I created recursive by myself without using LDAP_MATCHING_RULE_IN_CHAIN. Firstly I get groups of which the user is member of. I retrieve this groups with attribute "memberOf" - this attribute contains parent groups. And then I make same operation for parent groups until my search is finished. This works fast.

Grails, Spring Security LDAP Plugin

I'm trying to get the LDAP plugin work. I only want a LDAP authentication against an Active Directory but it seems that I'm missing something.
Config
grails {
plugins {
springsecurity {
userLookup.userDomainClassName = 'de.ac.dmf.security.User'
userLookup.authorityJoinClassName = 'de.ac.dmf.security.UserRole'
authority.className = 'de.ac.dmf.security.Role'
ldap {
context.managerDn = 'CN=dmf Systemuser,CN=Users,DC=dmf,DC=local'
context.managerPassword = 'Password1'
context.server = 'ldap://192.168.100.133:389/'
authorities{
groupSearchBase ='OU=Groups'
groupSearchFilter = '(member={0})'
retrieveGroupRoles = false
retrieveDatabaseRoles = false
defaultRole = 'USER'
ignorePartialResultException = true
}
search{
base = 'CN=Users,DC=dmf,DC=local'
filter = '(sAMAccountName={0})'
searchSubtree = true
}
// mapper.userDetailsClass = 'user'
// auth.hideUserNotFoundExceptions = false
useRememberMe = false
}
}
}
}
On every login I just get this exception
2011-04-29 08:49:09,129 [http-8080-1] DEBUG springsecurity.RequestHolderAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.AuthenticationServiceException: [LDAP: error code 32 - 0000208D: NameErr: DSID-031001E4, problem 2001 (NO_OBJECT), data 0, best match of:
'CN=Users,DC=dmf,DC=local'; remaining name 'CN=Users,DC=dmf,DC=local'
It doesn't matter which user from my AD I'm trying to authenticate. Is my configuration wrong?
I'm using
Grails 1.3.7
spring-security-core 1.1.2
spring-security-ldap 1.04
are you sure about your base configuration? Looks like OU=Users could work instead of CN=Users. Easiest way to figure this out is to use a tool like ad explorer (http://technet.microsoft.com/de-de/sysinternals/bb963907), connect to your AD, browse to a user and take a look at the path to the user...
Try using:
filter = '(&(sAMAccountName={0})(objectclass=user))'
That works on our AD.
You are missing the provider name list.
grails.plugins.springsecurity.providerNames = ['ldapAuthProvider',
'anonymousAuthenticationProvider',
'rememberMeAuthenticationProvider']

Categories

Resources