Thursday, May 20, 2010

Managing users and roles with WSO2 Identity Server open API

WSO2 Identity Server enables you to manage users and roles in your system with it's open web services API - so, any third party application can consume this API to handle authentication and authenrization with WSO2 Identity Server.

Following code sample illustrates following tasks and you can download the complete Eclipse project for the sample from here.

1. Authenticates a user
2. Creates a new role
3. Creates a user and add the user to a new role
4. Adds a value to a predefined custom attribute under the user profile
5. Checks whether a given user belongs to a given role.

Please unzip the attached zipped file and import it to Eclipse.

You need to have following in your classpath.

axiom-1.2.9.wso2v1.jar
axis2-1.6.0.wso2v1.jar
commons-codec-1.3.0.wso2v1.jar
commons-fileupload-1.2.0.wso2v1.jar
commons-httpclient-3.1.0.wso2v1.jar
httpcore-4.1.0.alpha1-wso2v1.jar
neethi-2.0.4.wso2v1.jar
org.wso2.carbon.authenticator.proxy-3.0.0.jar
org.wso2.carbon.logging-3.0.0.jar
org.wso2.carbon.um.ws.api-3.0.0.jar
org.wso2.carbon.user.core-3.0.0.jar
wsdl4j-1.6.2.wso2v1.jar
XmlSchema-1.4.6.wso2v1.jar

Please find all these jars inside [IS_HOME]\repository\components\plugins.
package org.wso2.identity.um.sample;

import java.util.HashMap;
import java.util.Map;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.authenticator.proxy.AuthenticationAdminStub;
import org.wso2.carbon.um.ws.api.WSRealmBuilder;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreManager;

public class IdentityServerClient {

 // ONE TIME TASKS WE NEED TO DO BEFORE EXECUTING THIS PROGRAM.

 // TASK - 1 , CREATE a LoginOnly role from IS UI Console
 // ===========================================================
 // 0. Login as admin/admin
 // 1. Go to Users and Roles
 // 2. Click on Roles
 // 3. Add New Role
 // 4. Role Name : loginOnly [please use this name, since it's referred within the code below]
 // 5. Click Next
 // 6. Select only the 'Login' permission
 // 7. Click Next
 // 8. No need to select any users
 // 9. Click Finish

 // TASK - 2 , CREATE a custom claim from IS UI Console
 // ===========================================================
 // 0. Login as admin/admin
 // 1. Go to Claim Management
 // 2. Click on http://wso2.org/claims
 // 3. Click on 'Add New Claim Mapping'
 // 3.1 Display Name : Business Phone
 // 3.2 Description : Business Phone
 // 3.3 Claim Uri : http://wso2.org/claims/businessphone
 // 3.4 Mapped Attribute : http://wso2.org/claims/businessphone
 // 3.5 Support by default : Checked
 // 3.6 The rest can be kept blank

 private final static String SERVER_URL = "https://localhost:9443/services/";
 private final static String APP_ID = "myapp";

 /**
  * @param args
  */
 public static void main(String[] args) {

  AuthenticationAdminStub authstub = null;
  ConfigurationContext configContext = null;
  String cookie = null;
  String newUser = "prabath2";

  System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
  System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");

  try {
   configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
     "repo", "repo/conf/client.axis2.xml");
   authstub = new AuthenticationAdminStub(configContext, SERVER_URL
     + "AuthenticationAdmin");

   // Authenticates as a user having rights to add users.
   if (authstub.login("admin", "admin", APP_ID)) {
    cookie = (String) authstub._getServiceClient().getServiceContext().getProperty(
      HTTPConstants.COOKIE_STRING);

    UserRealm realm = WSRealmBuilder.createWSRealm(SERVER_URL, cookie, configContext);
    UserStoreManager storeManager = realm.getUserStoreManager();

    // Add a new role - with no users - with APP_ID as the role name

    if (!storeManager.isExistingRole(APP_ID)) {

     storeManager.addRole(APP_ID, null, null);
     System.out.println("The role added successfully to the system");
    } else {
     System.out.println("The role trying to add - already there in the system");
    }

    if (!storeManager.isExistingUser(newUser)) {
     // Let's the this user to APP_ID role we just created.

     // First let's create claims for users.
     // If you are using a claim that does not exist in default IS instance,
     Map claims = new HashMap();

     // TASK-1 and TASK-2 should be completed by now.
     // Here I am using an already existing claim
     claims.put("http://wso2.org/claims/businessphone", "0112842302");

     // Here we pass null for the profile - so it will use the default profile.
     storeManager.addUser(newUser, "password", new String[] { APP_ID, "loginOnly" },
       claims, null);
     System.out.println("The use added successfully to the system");
    } else {
     System.out.println("The user trying to add - already there in the system");
    }

    // Now let's see the given user [newUser] belongs to the role APP_ID.
    String[] userRoles = storeManager.getRoleListOfUser(newUser);
    boolean found = false;

    if (userRoles != null) {
     for (int i = 0; i < userRoles.length; i++) {
      if (APP_ID.equals(userRoles[i])) {
       found = true;
       System.out.println("The user is in the required role");
       break;
      }
     }
    }
    
    if (!found){
     System.out.println("The user is NOT in the required role");
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

9 comments:

id said...

test

juan carlos said...

Hi,

I need managing users and roles with WSO2 Governance Registry. I try your example but Governance Registry has not the service RemoteUserStoreManagerService.
Do you know if I can import/install this service?
Do you know if there are any alternative?

Thanks,
JC

Raju said...

Hi Prabhat,
It seems the code is very old one..Not even all the lib jars are not available ..Can you post the latest one which should be supported by 3.2.0?

Stepan Bahdikyan said...
This comment has been removed by the author.
Stepan Bahdikyan said...
This comment has been removed by the author.
Stepan Bahdikyan said...

Hi Prabhat,
The code is really old, could you post a new version?
Thanks.

Yumani Ranaweera said...

Hi Parabath,

I'm getting following exception when executing the code;
I've used jars from is-4.1.0. I also added org.wso2.carbon.securevault_4.0.0.jar. But it doesn't hv org.wso2.securevault.SecretResolverFactory. I'm not sure if what I was trying is correct. Could you please help.

Exception in thread "main" java.lang.NoClassDefFoundError: org/wso2/securevault/SecretResolverFactory
at org.apache.axis2.deployment.AxisConfigBuilder.populateConfig(AxisConfigBuilder.java:92)
at org.apache.axis2.deployment.DeploymentEngine.populateAxisConfiguration(DeploymentEngine.java:854)
at org.apache.axis2.deployment.FileSystemConfigurator.getAxisConfiguration(FileSystemConfigurator.java:116)
at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContext(ConfigurationContextFactory.java:64)
at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContextFromFileSystem(ConfigurationContextFactory.java:210)
at org.wso2.identity.um.sample.IdentityServerClient.main(IdentityServerClient.java:62)
Caused by: java.lang.ClassNotFoundException: org.wso2.securevault.SecretResolverFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 6 more

Thanks,
Yumani

jeancs said...

@Yumani

I tried to do it with is-4.1.0 too and had the same error you got. I resolved it by adding the following file in the java project : org.wso2.securevault_1.0.0.wso2v2.jar

prasad chowdary said...

Hi ,

I am new to WSO2 Identity Server.I tried to download SVN 4.1.0,i am getting build errors.Will you please guide me where can i download build able source version and how to build source code