Command-line Samples: OpenSSO Client SDK

After successfully completing the OpenSSO Client SDK web-based samples (see sidebar for links), I moved to the command-line samples.

IMPORTANT: Be sure to run all the scripts discussed in this entry one level up from the directory in which they are found as in:

scripts/setup.sh

and so on.

After unzipping and deploying fam-client-jdk15.war, I make the scripts in the sdk directory executable by running chmod 755 \*.sh. Because I am using JDK 1.5 the following message was displayed:
Note: source/com/sun/identity/samples/authentication/Login.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
This message refers to the components in the script needed for JDK 1.4 so it can be ignored. Following I compiled the samples by running compile-samples.sh. Then I ran the following sample scripts.

setup.sh
Login.sh
CommandLineSSO.sh
CommandLineIdrepo.sh
CommandLineLogging.sh
SSOTokenSample.sh

When you run setup.sh you are creating AMConfig.properties and populating it with values based on your deployment. Main.java is the code used.

NOTE: Although the server side AMConfig.properties has been deprecated for current and future versions of OpenSSO in favor of OpenDS, the Client SDK still uses it's own version of the file.

The following is output to the screen with my input in italics.
debug directory: /opensso/debug
password of OpenSSO: admin123
protocol: http
server name:ilsdev2.red.iplanet.com
port: 8080
URI: opensso (no slash)
Naming: /namingservice
This script creates AMConfig.properties in the sdk/resources directory.

The first time I ran Login.sh (which logs in and then logs out the user based on Login.java), I got this error:
com.sun.identity.authentication.spi.AuthLoginException: Failed to create new Authentication Context: Naming Service is not available.
       at com.sun.identity.authentication.AuthContext.login(AuthContext.java:534)
       at com.sun.identity.authentication.AuthContext.login(AuthContext.java:377)
       at com.sun.identity.samples.authentication.Login.getAuthContext(Login.java:64)
       at com.sun.identity.samples.authentication.Login.main(Login.java:206)
It turns out that com.iplanet.am.naming.url in AMConfig.properties (which takes as a value the URL of the OpenSSO Naming Service) did not have a defined port number. I'm not sure how this happened because every other URL had taken the value from my setup input. Once I modified the property and restarted glassfish, Login.sh ran successfully:
Realm (e.g. /): /
Login module name (e.g. DataStore or LDAP): DataStore
Login locale (e.g. en_US or fr_FR): en_US
DataStore: Obtained login context
User Name:amadmin
Password:admin123
Login succeeded.
Logged Out!!
NOTE: If you want to chose LDAP, you have to configure the LDAP authentication module using the OpenSSO console. Be aware that the OpenDS server installed with OpenSSO is intended for configuration only.

Next I ran CommandLineSSO.sh which demonstrates how to retrieve a user profile using CommandLineSSO.java . I got an error that informed me to check the com.sun.identity.agents.app.username and the com.iplanet.am.service.password properties in AMConfig.properties. Of the two, com.iplanet.am.service.password had no value so, after some internal email investigation, I populated it with the correct password, changeit. I saved the file, restarted Glassfish, and ran CommandLineSSO.sh again. This time it was successful. The following output was displayed:

Organization: /
DataStore: Obtained login context
User Name:amadmin
Password:admin123
Successful authentication ...
User Name: id=amadmin,ou=user,dc=opensso,dc=java,dc=net
User Attributes:
dn=[uid=amAdmin,ou=people,dc=opensso,dc=java,dc=net]
roles=[Top-level Admin Role]
inetuserstatus=[Active] 
Next I ran CommandLineIdrepo.sh which functioned without a hitch. And it was F-U-N, FUN! You can perform any number of operations on the identity repository. The source files for this sample can be found here. I created the sub realm CLRealm and deleted aaaa an identity I had previously created. CommandLineIdrepo.sh ran as follows:
Userid [amAdmin]: amadmin
Userid amadmin's password [openssoxxx]: admin123
Realm [/]:
==>Authentication SUCCESSFUL for user amadmin
AMIdentity realm name for realm '/' is 'dc=opensso,dc=java,dc=net'
getting subrealms
Realm '/' has no subrealms


Currently in realm '/'.
Realm '/' has no subrealms

  AMIdentityRepository operations
        0:  Select (sub)Realm           1:  Create Identity
        2:  Delete Identity             3:  Get Allowed Operations
        4:  Get Supported IdTypes       5:  Search/Select Identities
        6:  Return to / realm           7:  Exit

Enter selection: 1
    Supported IdTypes:
        0: user
        1: agent
        2: agentonly
        3: agentgroup
        4: realm
        5: No selection
Select type: [0..3]: 4
    No realms found.
Enter idName to create: CLRealm
CLRealm active/inactive [a,i]: a
    Created realm identity 'CLRealm' isExists = false
    Current list of realms:
        CLRealm
idRepoProcessing IdRepoException creating 'IdType: realm': Plug-in com.sun.identity.idm.plugins.internal.AgentsRepo: Unable to read attributes.

Currently in realm '/'.
Realm '/' has no subrealms

  AMIdentityRepository operations
        0:  Select (sub)Realm           1:  Create Identity
        2:  Delete Identity             3:  Get Allowed Operations
        4:  Get Supported IdTypes       5:  Search/Select Identities
        6:  Return to / realm           7:  Exit

Enter selection: 2
    Supported IdTypes:
        0: user
        1: agent
        2: agentonly
        3: agentgroup
        4: realm
        5: No selection
Select type: [0..3]: 0
Found 6 entries of type user.
AMIdentities:
        0: amAdmin
        1: amldapuser
        2: dsameuser
        3: anonymous
        4: aaaa
        5: amService-URLAccessAgent
        6: No selection
Select id: [0..6]: 4
    Current list of users:
        amAdmin
        amldapuser
        dsameuser
        anonymous
        aaaa
        amService-URLAccessAgent

Currently in realm '/'.
Realm '/' has no subrealms

  AMIdentityRepository operations
        0:  Select (sub)Realm           1:  Create Identity
        2:  Delete Identity             3:  Get Allowed Operations
        4:  Get Supported IdTypes       5:  Search/Select Identities
        6:  Return to / realm           7:  Exit

Enter selection: 7
idRepoProcessing: user 'amadmin' logged out
Next I ran CommandLineLogging.sh which demonstrates log writing as well as the login process. The script calls LogSample.java. You will need to authenticate two users: the subject of the LogRecord and the logger. In the following output, bbbb is the subject and amadmin is the logger.
Subject Userid [user1]: bbbb
Subject Userid bbbb's password [user1password]: bbbb
Log file [TestLog]: accepted default
Log message [Test Log Record]: accepted default
LoggedBy Userid [amadmin]: accepted default
LoggedBy Userid's password [amadminpswd]: admin123
Realm [/]: accepted default
==>Authentication SUCCESSFUL for user bbbb
==>Authentication SUCCESSFUL for user amadmin
LogSample: Logging Successful !!! 
TestLog is created in /opensso/log. Here is TestRecord the logging record written to TestLog.
#Version: 1.0
#Fields: time   Data    ModuleName      MessageID       Domain  ContextID       LogLevel        LoginID NameID  IPAddr  LoggedBy        HostName

"2007-12-18 08:39:36"   "Test Log Record"       MyModule        "Not Available" dc=opensso,dc=java,dc=net       713eba0d5788db2301      INFO    id=bbbb,ou=user,dc=opensso,dc=java,dc=net  "Not Available" null    id=amadmin,ou=user,dc=opensso,dc=java,dc=net    192.18.87.132 
SSOTokenSample.sh is an SSOToken verification sample. You enter an SSOTokenID and the script verifies that it is a valid, authenticated token. SSOTokenSample.java demonstrates this action and how to use other functions of the SSO API.

Before running this sample, you will need an SSO Token ID. I went back to the web-based Service Configuration Sample, ran it and copied the ID that was displayed. Then I ran SSOTokenSample.sh and got the following output.
Enter SSOToken ID:  AQIC5wM2LY4SfcyCY9VHtZbfWtJFuZShI3N1jX5fO5fFuXY=@AAJTSQACMDE=#
SSOToken host name: 192.xx.xx.xxx [secret stuff]
SSOToken Principal name: id=amadmin,ou=user,dc=opensso,dc=java,dc=net
Authentication type used: DataStore
IPAddress of the host: 192.xx.xx.xxx [secret stuff]
SSO Token validation test Succeeded.
Token ID: AQIC5wM2LY4SfcyCY9VHtZbfWtJFuZShI3N1jX5fO5fFuXY=@AAJTSQACMDE=#
Property: TimeZone: PST
Property: County: SantaClara 
        
    
Comments:

Hi,

I am trying to connect to the openSSO with the following client:

/\*
\* OpenSSOConnect.java
\*
\* Created on November 2, 2006, 11:18 AM
\*
\* To change this template, choose Tools | Template Manager
\* and open the template in the editor.
\*/

/\*\*
\*
\* @author steffo
\*/

// OpenSSO installation has a default realm 'init8' as well as an authentication chain 'init8'

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.ChoiceCallback;
import javax.security.auth.callback.ConfirmationCallback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextInputCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

import com.iplanet.am.util.SystemProperties;
import com.iplanet.sso.SSOToken;
import com.sun.identity.authentication.AuthContext;
import com.sun.identity.idm.AMIdentity;
import com.sun.identity.idm.IdUtils;
import com.sun.identity.security.AdminTokenAction;

public class OpenSSOConnect
{
public static void main(String[] argv)
{
boolean remote = false;
if (argv.length > 0)
{
String r = argv[0];
if (r.equalsIgnoreCase("remote"))
{
remote = true;
}
}
Properties props = new Properties();

try
{
FileInputStream amconfig = new FileInputStream("C:/Glass/OpenSSOServerConfig/AMConfig.properties");
props.load(amconfig);
}
catch (IOException e)
{
System.out.println("AMConfig.properties was not found");
}

//props.setProperty("com.iplanet.services.debug.level", "message");
// props.setProperty("com.iplanet.am.naming.ignoreNamingService", "true");
//props.setProperty("Organization", "dc=eglue,dc=com");

props.setProperty("com.iplanet.am.serverMode","false");
//props.setProperty("com.iplanet.am.naming.failover.url","http://localhost:8080/opensso/failover");
// props.setProperty("com.sun.identity.agents.app.username","amadmin");
// props.setProperty("com.iplanet.am.service.password","admin123");

//props.setProperty("am.encryption.pwd","qM+fV2jBTecm+hqWAT29Z6RmJ6B0xecP");//begin
// props.setProperty("com.iplanet.am.cookie.encode","false");
//props.setProperty("com.iplanet.am.cookie.name","iPlanetDirectoryPro");
// props.setProperty("com.sun.identity.plugin.session.class","com.sun.identity.plugin.session.impl.FMSessionProvider");//End
//AQIC5wM2LY4Sfcxvakm6PKWlQ4zgzMrwKYohIbRFGnnpxoM=@AAJTSQACMDE=#
//remote=true;
if (remote)
{
//props.setProperty("com.iplanet.am.sdk.package", "com.iplanet.am.sdk.remote");
}
else
{
//props.setProperty(AdminTokenAction.AMADMIN_MODE, "true");
}
System.out.println("Properties set");
SystemProperties.initializeProperties(props);
try
{
SSOToken token = getSSOToken();
AMIdentity amId = IdUtils.getIdentity(token, "id=testUser,ou=user,dc=eglue,dc=com");
Map map = amId.getAttributes();
System.out.println (map);
System.out.println(map.get("nsroledn"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

public static SSOToken getSSOToken() throws Exception
{
return getSSOToken("eglue", "amadmin", "admin123");
}

protected static SSOToken getSSOToken(String org, String uid,
String password) throws Exception
{
AuthContext ac = new AuthContext(org);
ac.login(AuthContext.IndexType.SERVICE, "ldapService");
Callback[] callbacks = null;
if (ac.hasMoreRequirements())
{
callbacks = ac.getRequirements();
if (callbacks != null) {
try {
addLoginCallbackMessage(callbacks, uid, password);
ac.submitRequirements(callbacks);
} catch (Exception e) {
debugMessage("Login failed!!");
debugMessage("--> " + ac.getLoginException().getMessage());
e.printStackTrace();
return null;
}
}
}
if (ac.getStatus() == AuthContext.Status.SUCCESS)
{
debugMessage("Login success!!");
}
else
if (ac.getStatus() == AuthContext.Status.FAILED)
{
debugMessage("Login has failed!!");
debugMessage("--> " + ac.getLoginException().getMessage());
}
else
if( ac.getStatus() == AuthContext.Status.IN_PROGRESS )
{
// This may happen when the password is about to expire and must be reset.
// Analyze the error message to be sure what is going on.
debugMessage( "Login is in progress !" );
if( ac.hasMoreRequirements() )
{
callbacks = ac.getRequirements();
if( callbacks != null )
{
debugMessage( "Callbacks for new password will be processed !" );
try
{
addNewPasswordCallbackMessage( callbacks, uid, password, "" );
ac.submitRequirements( callbacks );
}
catch( Exception e )
{
debugMessage( "Login failed while processing new password callbacks." );
debugMessage("--> " + ac.getLoginException().getMessage());
e.printStackTrace();
return null;
}
}
}
if( ac.getStatus() == AuthContext.Status.SUCCESS )
debugMessage( "Login success after switch to new password!" );
else
{
debugMessage( "Login failed after switch to new password!" );
debugMessage("--> " + ac.getLoginException().getMessage());
}
}
else
{
debugMessage("Unknown status: " + ac.getStatus());
debugMessage("--> " + ac.getLoginException().getMessage());
}
SSOToken token = ac.getSSOToken();
//ac.abort();
return token;
}

// Get user's inputs and set them to callback array.
static void addLoginCallbackMessage(Callback[] callbacks, String uid,
String password) throws UnsupportedCallbackException
{
debugMessage("begin addLoginCallbackMessage()");
int i = 0;
try
{
for (i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof TextOutputCallback)
{
debugMessage("Got TextOutputCallback");
// Display the message according to the specified type
TextOutputCallback toc = (TextOutputCallback) callbacks[i];
switch (toc.getMessageType()) {
case TextOutputCallback.INFORMATION:
debugMessage(toc.getMessage());
break;
case TextOutputCallback.ERROR:
debugMessage("ERROR: " + toc.getMessage());
break;
case TextOutputCallback.WARNING:
debugMessage("WARNING: " + toc.getMessage());
break;
default:
debugMessage("Unsupported message type: "
+ toc.getMessageType());
}
}
else
if (callbacks[i] instanceof NameCallback)
{
debugMessage("Got NameCallback");
NameCallback nc = (NameCallback) callbacks[i];
nc.setName(uid);
}
else
if (callbacks[i] instanceof PasswordCallback)
{
debugMessage("Got PasswordCallback");
PasswordCallback pc = (PasswordCallback) callbacks[i];
pc.setPassword(new String(password).toCharArray());
}
else
if (callbacks[i] instanceof TextInputCallback)
{
debugMessage("Got TextInputCallback");
// prompt for text input
TextInputCallback tic = (TextInputCallback) callbacks[i];
// ignore the provided defaultValue
System.err.print(tic.getPrompt());
System.err.flush();
tic.setText((new BufferedReader(new InputStreamReader(
System.in))).readLine());

}
else
if (callbacks[i] instanceof ChoiceCallback)
{
debugMessage("Got ChoiceCallback");
// prompt for choice input
ChoiceCallback cc = (ChoiceCallback) callbacks[i];
System.err.print(cc.getPrompt());

String[] strChoices = cc.getChoices();
for (int j = 0; j < strChoices.length; j++)
{
System.err
.print("choice[" + j + "] : " + strChoices[j]);
}
System.err.flush();
cc.setSelectedIndex(Integer.parseInt((new BufferedReader(
new InputStreamReader(System.in))).readLine()));
}
}
}
catch (Exception e)
{
throw new UnsupportedCallbackException(callbacks[i],
"Callback exception: " + e);
}
}

static void addNewPasswordCallbackMessage( Callback[] callbacks,
String uid,
String oldPassword,
String newPassword ) throws UnsupportedCallbackException
{
int pwdCount = 0;
int i = 0;
try
{
for (i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof TextOutputCallback)
{
debugMessage( "Got TextOutputCallback while setting new password." );
// simply display the message
TextOutputCallback toc = (TextOutputCallback) callbacks[i];
debugMessage(toc.getMessage() + " :" + toc.getMessage() );
}
else
if (callbacks[i] instanceof NameCallback)
{
debugMessage( "Got NameCallback while setting new password - this should not happen !" );
debugMessage( "Maybe you hit the next login module." );
}
else
if (callbacks[i] instanceof PasswordCallback)
{
debugMessage( "Got PasswordCallback while setting new password." );
PasswordCallback pc = (PasswordCallback) callbacks[i];
// set first password callback with value of old password, the others with the new one
if( pwdCount == 0 )
pc.setPassword( new String( oldPassword ).toCharArray() );
else
pc.setPassword( new String( newPassword ).toCharArray() );
pwdCount++;
}
else
if (callbacks[i] instanceof ConfirmationCallback)
{
debugMessage( "Got ConfirmationCallback while setting new password !" );
ConfirmationCallback cc = (ConfirmationCallback) callbacks[i];
// "0" is the index of SUBMIT
cc.setSelectedIndex( 0 );
}
else
if (callbacks[i] instanceof TextInputCallback)
{
debugMessage( "Got TextInputCallback while setting new password - this should not happen !" );
}
else
if (callbacks[i] instanceof ChoiceCallback)
{
debugMessage( "Got ChoiceCallback while setting new password - this should not happen !" );
}
}
}
catch( Exception e )
{
throw new UnsupportedCallbackException( callbacks[i], "Callback exception: " + e );
}
}

static void debugMessage(String msg)
{
System.out.println(msg);
}

}

When I run it from eclipse as a standalone I get the correct results but when I am running it from weblogic context (exactly the same code with the appropriate jars in the classpath) I am getting the following error :

com.sun.identity.authentication.spi.AuthLoginException: Failed to create new Authentication Context: {0}
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:530)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:315)

I saw in your blog that you face with the same error - and I checked the naming url again and it configure right.

Please help/advise - I am working on it more then a week.

Thanks in advance!!!

Eliad Dahan.

Posted by Eliad Dahan on December 26, 2007 at 11:58 PM PST #

Hi All
I tried to configure SAM 7.1 with SIM 7.1 as an Authenticated resource.
but when i tried to configure SAM as a resource in SIM .....during ...test configuration it gives me the error.." cannot login user "amadmin" with specified password . com.sun.identity.authentication.spi.AuthLoginException: Failed to create new Authentication Context: Naming Service is not available".

Posted by Amit Bansal on May 11, 2008 at 06:39 PM PDT #

While i am trying to run the login sample i am getting the error as below:

Exception in thread "main" java.lang.NullPointerException
at com.sun.identity.shared.xml.XMLUtils.getRootNode(XMLUtils.java:356)
at com.sun.identity.authentication.AuthContext.getCallbacks(AuthContext.java:1608)
at com.sun.identity.authentication.AuthContext.hasMoreRequirements(AuthContext.java:849)
at com.sun.identity.samples.Login1.login(Login.java:161)
at com.sun.identity.samples.Login1.main(Login.java:207)

Can anybody here help me out overcoming this

Thanks
-Gaurav

Posted by Gaurav Sharma on July 15, 2008 at 02:28 AM PDT #

Gauruav, I just now got this comment. Sorry for the delay. If you haven't found the answer, try asking at users@opensso.dev.java.net.

Posted by DocTeger on August 07, 2008 at 04:08 AM PDT #

Hi Doc,

I'm trying to run the CommandLineSSO.bat file and I modified my AMConfig.properties to the following as you suggested above:

com.sun.identity.agents.app.username=amAdmin
com.iplanet.am.service.password=changeit

However, I'm still getting the same error:

\\CommandLineSSO.bat
Organization: /
DataStore: Obtained login context
User Name:amadmin
Password:testxxxx
Successful authentication ...
User Name: id=amadmin,ou=user,dc=opensso,dc=java,dc=net
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.sun.identity.sm.ServiceManager.(ServiceManager.java:77)
at com.sun.identity.idm.IdUtils.initialize(IdUtils.java:127)
at com.sun.identity.idm.IdUtils.(IdUtils.java:123)
at com.sun.identity.samples.sso.CommandLineSSO.main(CommandLineSSO.java:
72)
Caused by: com.sun.identity.security.AMSecurityPropertiesException: AdminTokenAc
tion: FATAL ERROR: Cannot obtain Application SSO token.
Check AMConfig.properties for the following properties
com.sun.identity.agents.app.username
com.iplanet.am.service.password
at com.sun.identity.security.AdminTokenAction.run(AdminTokenAction.java:
237)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.identity.sm.SMSEntry.initSMSObject(SMSEntry.java:382)
at com.sun.identity.sm.SMSEntry.initializeClass(SMSEntry.java:216)
at com.sun.identity.sm.SMSEntry.(SMSEntry.java:206)
... 4 more
Terminate batch job (Y/N)? \^C

Any suggestions?

Thanks,
Tim

Posted by Tim on September 17, 2008 at 06:53 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

docteger

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today