Java Code to fetch Session Store attribute values - java

I am writing an Assertion Generator Plugin in Java to fetch a user details from Session Store and modify the values in Assertion(SAML 2.0) accordingly.
I am able to identify the method(Link) using which I can pull the user values from Session Store (agentAPIObject.getSessionVariables()) based on SessionID, but, I am having trouble writing a code to fetch specific parameters from the session store. (speficially around setting values for Attribute method and making it as an array)
Can someone post a sample code if you have ever seen/written around it, so that I can fetch user attributes from Session Store.
I am having trouble understanding Java docs around it.
Thanks in advance,

The API mentions this:
responseAttributeList - On successful return from this method (YES is
returned), this output parameter contains the retrieved variable names
and their values. If the method returns UNRESOLVED, this parameter
includes variables that could not be retrieved.
You'll need to create two AttributeList Objects. If the response of getSessionVariables(...) is YES, then the variable responseAttributeList will contain the session variables. Since Java uses references, that same variable responseAttributeList will be updated. You can then use getAttributeAt(...) to access the Attribute Objects.
String sessionID = "sampleID";
ResourceContextDef rcd = //whatever it needs to be equal to
AttributeList requestAttributeList = new AttributeList();
AttributeList responseAttributeList = new AttributeList();
if(getSessionVariables(sessionId, rcd, requestAttributeList, responseAttributeList) == YES){
Attribute att = responseAttributeList.getAttributeAt(0);//or whatever index.
}
Remember to carefully read the API.
NOTE: This is just pseudo code. I have not tested this. However, this should be plenty enough to get you going where you need to.

Related

How to pass a JavaScript array to an XPages Java Controller

I'm working with jQuery DataTables. I have it listing out a view and have checkboxes to select multiple documents. I'm able to get the selected keys into session scope via this client side JavaScript code :
<xp:this.script><![CDATA[// Build array of selected rows
var myTableApi = x$("inventoryTable").DataTable();
var count = myTableApi.rows( { selected: true } ).count();
var dataArr = [];
var rowData = myTableApi.rows( { selected: true } ).data();
$.each($(rowData),function(key,value){
dataArr.push(value[3]);
});
// Push that to the requestScope
setScopeValue("session", "rowCount", count);
setScopeValue("session", "rowIds", dataArr);]]></xp:this.script>
Once the id's are in Scope I change pages and then I want to load them into my Java pageController.
I can easily use a variable resolver to get ahold of "rowIds". But I'm not sure how to get it into Java so I could work with it. Ideally I'd like it to be List or Set or something similar.
In Java, how can I convert this JavaScript Array to a Collection based object?
Thanks!
There are a few tricks to do here.
First, since the particular implementation of your setScopeValue function converts all values to a string before sending them to the server, it's important to do setScopeValue("session", "rowIds", XSP.toJson(dataArr)). That way, the value stored on the server will be ["foo", "bar", "baz"] instead of foobarbaz.
Secondly, the best way to get to the session-scoped value in Java would be via ExtLibUtil.getSessionScope().get("rowIds").
That value will be a string, though, and not an array type, so it'll have to be parsed from JSON. Using the IBM Commons JSON capabilities, that can be done with:
List<?> rowIds = (List<?>)JsonParser.fromJson(JsonJavaFactory.instance, ExtLibUtil.getSessionScope().get("rowIds"))
for(Object rowIdObj : rowIds) {
String rowId = StringUtil.toString(rowIdObj);
// do stuff with each ID here
}
You can also potentially case it directly to a List<String>, since Java's generics are really just hints for compiler-generated code, and not really enforced in the objects themselves, but there you run the risk of a ClassCastException if the incoming List contains any non-string types.

Error reading objects from Gemalto smartcard using IAIK pkcs11wrapper

I'm trying to read the public certificate names from a smartcard to display to the user before they sign a file using a gemalto smartcard.
I've followed the getInfo example from iaikPkcs11Wrapper demos as below :
Module pkcs11Module = Module.getInstance(settings.getCryptoDll());
Slot[] slotList;
try{
slotList = pkcs11Module.getSlotList(true);
}catch(TokenException tex){//module is not initialised
tex.printStackTrace();
pkcs11Module.initialize(new DefaultInitializeArgs());
slotList = pkcs11Module.getSlotList(true);
}
for (Slot slot : slotList) {
Token token = slot.getToken();
iaik.pkcs.pkcs11.Session session = token.openSession(true, SessionReadWriteBehavior.RO_SESSION, null, null);
session.findObjectsInit(null);
Object[] objects = new Object[0];
try {
objects = session.findObjects(1);
This fails always at the line objects = findObjects(1); with a CKR_TEMPLATE_INCONSISTENT exception.
As I understand from the documentation session.findObjectsInit(null) should just return all accessible objects on the card and you can then compare them for type.
I have various smartcards and they all fail like this, I've also tried calling session.findObjectsInit(tempObj) with a GenericTemplate object and a X509PublicKeyCertificate which both return the same exception, and with an X509AttributeCertificate which returns no objects but does not throw the exception.
I'd appreciate any pointers anyone can give. Or do I need to create a matching template object using GenericTemplate? I'm unsure why I'm getting the exception as I thought passing the object into the getObjectInit method filtered for thet object so anything returned should match.
EDIT
I've subsequently tried with other templates and ones for objects not on the card just return an empty array- no exception and ones I think are on the cards just throw the ckr_template_inconsistent exception, any help would be gratefully received.
EDIT2
I've now tried with some new 'V3' cards, which do infact work, all my test cards work using another technique (we currently use capicom via com4J for signing), so maybe there is an issue with the iaik wrapper, or gclib.dll (or me).

Can't convert Apigee Java Object response to string

I'm using the GetAPIProduct policy (see http://apigee.com/docs/gateway-services/content/retrieve-api-product-settings-using-getapiproduct
) to get a list of scopes. Then in a JavaScript callout, I try to reference that list of scopes, but instead of text I get back something like this (the hex chunk at the end changes with each call):
[Ljava.lang.String;#19baa7ed
There doesn't seem to be anything I can do to turn it into an array I can access using Javascript. I'm in a Free org so Java is not an option. I've tried String(), myvar.toString() and even the Rhino context.javaToJs which doesn't seem to exist in Apigee.
Any ideas how I can either convert this to a string?
It turns out that the value of getapiproduct.{policyname}.apiproduct.scopes is a zero-based array of objects. Each of those objects, though, can be converted to a string that is a scope name.
So here's how you access the array of scopes:
var scopeArray=context.getVariable("getapiproduct.RetrieveProductInfo.apiproduct.scopes");
// you can use either of these methods to convert the array elements
var firstElement = String(scopeArray[0]);
var secondElement = scopeArray[1]+'';
var scopeArrayLen = scopeArray.length;
This isn't an answer to the question, but is some additional information that may be valuable.
The GetAPIPRoductInfo gets the list of scopes on a product. Conversely, the GetOAuthV2Info policy gets information about an OAUthV2 token. Assuming you have a token you could do something like this:
<GetOAuthV2Info name='GetOAuthV2Info-TokenScopes'>
<!-- use one of the following: a referenced variable or -->
<!-- an explicitly passed access_token -->
<AccessToken ref='access_token'/>
<!--
On Success, the following flow variables will be set.
oauthv2accesstoken.{policy_name}.access_token
oauthv2accesstoken.{policy_name}.scope
oauthv2accesstoken.{policy_name}.refresh_token
oauthv2accesstoken.{policy_name}.accesstoken.{custom_attribute_name}
oauthv2accesstoken.{policy_name}.developer.id
oauthv2accesstoken.{policy_name}.developer.app.name
oauthv2accesstoken.{policy_name}.expires_in
oauthv2accesstoken.{policy_name}.status
-->
</GetOAuthV2Info>
Then you can use that information in a subsequent JS callout to check the scopes for the token against whatever requirement you have:
// checkScope.js
// ------------------------------------------------------------------
var varname = 'oauthv2accesstoken.GetOAuthV2Info-TokenScopes.scope',
approvedScopes = context.getVariable(varname),
check = false;
approvedScopes = approvedScopes.split(' ');
// approvedScopes is now a JavaScript array of strings, that lists
// the scopes the user approved for the requesting client (app).
//
// You can now compare that list against the scopes required
// for an operation or resource, and then set a variable
// determining whether the token is good for the request.
context.setVariable('scopeCheck.ok', check);

Upsert for LDAP directory in Java

I'm attempting to execute an Upsert using the Novell JLDAP library, unfortunately, I'm having trouble finding an example of this. Currently, I have to:
public EObject put(EObject eObject){
Subject s = (Subject) eObject;
//Query and grab attributes from subject
LDAPAttributes attr = resultsToAttributes(getLDAPConnection().get(s));
//No modification needed - return
if(s.getAttributes().equals(attr)){
return eObject;
} else {
//Keys:
//REPLACE,ADD,DELETE, depending on which attributes are present in the maps, I choose the operation which will be used
Map<String,LDAPAttribute> operationalMap = figureOutWhichAttributesArePresent(c.getAttributes(),attr);
//Add the Modifcations to a modification array
ArrayList<LDAPModification> modList = new ArrayList<LDAPModification>();
for(Entry entry: operationalMap.getEntrySet()){
//Specify whether it is an update, delete, or insert here. (entry.getKey());
modList.add(new LDAPModification(entry.getKey(),entry.getValue());
}
//commit
connection.modify("directorypathhere",modList.toArray(new LDAPModification[modList.size()]));
}
I'd prefer to not have to query on the customer first, which results in cycling through the subject's attributes as well. Is anyone aware if JNDI or another library is able to execute an update/insert without running multiple statements against LDAP?
Petesh was correct - the abstraction was implemented within the Novell library (as well as the UnboundId library). I was able to "upsert" values using the Modify.REPLACE param for every attribute that came in, passing in null for empty values. This effectively created, updated, and deleted the attributes without having to parse them first.
In LDAP, via LDIF files, an upset would be a single event with two steps. A remove and add of a value. This is denoted by a single dash on a line, between the remove then the add.
I am not sure how you would do it in this library. I would would try to modList.remove and then modList.add one after another and see if that works.

HttpSession, session.getAttribute(), problem

I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:
Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);
Thanks.
This code intends to save back the modified vector represented by Register session attribute.
However you dont need to set the attribute back even after some elements are removed or added because its the reference anyways thats stored in session and any changes to it are essentially being applied to the same object.
Because Register attribute may be set from some other place (like. from jsp(in bad case),Servlet or Filter . . )
The only explanation I can think of is: first of all you you retrieve the vector, then make the change and after store it back into session object.
The code is either broken or the setAttribute() is futile.
If you get a mutable container (like a list or a vector) from the session, then it's not necessary to put it again into the session. It's the equivalent of this code:
session.setAttribute("Register", buylist);
session.setAttribute("Register", buylist);
session.setAttribute("Register", buylist);
None but the first line have an effect.
The other possibility is that the code has a bug and what really was meant was this:
Vector buylist = session.getAttribute("Register");
if( buylist == null ) {
buylist = new Vector();
session.setAttribute("Register", buylist);
}
i.e. create a new vector if it doesn't exist already.

Categories