Home > Articles > Programming > Java

Like this article? We recommend

Defining Realms in SJSAS

The application server supports five kinds of realms, but three of them are used most often: file realms, JDBC realms, and certificate realms.

File Realm

In a file realm, users and groups are stored in a file. This realm is represented by the following class:

com.sun.enterprise.security.auth.realm.file.FileRealm

By default, SJSAS contains two file realms:

  • file has the following corresponding file:
    {SJSAS_HOME}\domains\domain1\config\keyfile
  • admin-realm has the following corresponding file:
    {SJSAS_HOME}\domains\domain1\config\admin-keyfile

Initially, admin-realm contains the administrator's username and password (in an encrypted format), and the group to which this user belongs, which is asadmin by default.

JDBC Realm

In a JDBC realm, users and groups are stored in a database. This realm is represented by the following class:

com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm

By default, SJSAS doesn't contain JDBC realms.

Certificate Realm

In a certificate realm, users' identities are set up in the SJSAS security context and populated with user data obtained from cryptographically verified client certificates. This realm is represented by the following class:

com.sun.enterprise.security.auth.realm.certificate.CertificateRealm

By default, SJSAS contains a realm named certificate.

Creating a File Realm in SJSAS

Following are the basic steps to declare a new file realm in SJSAS:

  1. Start the Sun Java System Application Server.
  2. Launch the Admin Console in your favorite browser (by default, the URL is http://localhost:4848/asadmin).
  3. Log into the Admin Console. Provide a name and the password of a user in the admin-realm who belongs to the asadmin group.
  4. In the Admin Console tree (left pane), expand the Configuration > Security node and select the Realms node. In the right pane, you should see a table with the available realms (see Figure 1).
  5. Click the New button above the table to open the New Realm wizard.
  6. In this wizard, we need to fill in some fields. Start by entering a realm name in the Name field (for example, type MyFileRealm).
  7. Next, select the realm type. From the drop-down list, select the option com.sun.enterprise.security.auth.realm.file.FileRealm. This will indicate that the new realm is a file realm.
  8. Continue by indicating a Java Authentication and Authorization Service (JAAS) context. By default, this context is fileRealm, and it's best to leave this setting unmodified. (We won't go into this option in detail here.)
  9. In the last mandatory field, enter the path and name of the file that stores usernames and passwords. To indicate a file path relative to the SJSAS installation folder, use the property ${com.sun.aas.instanceRoot} (for example, my setup uses C:\Sun\SDK\domains\domain1 folder). Our filename is myFile and it's stored in the folder ${com.sun.aas.instanceRoot}/config (this file will be created automatically).
  10. At this point, we could assign a group to the realm (using the Assign Group field), but let's just leave this field empty for this example.
  11. Click OK to finish configuring the new file realm (see Figure 2).

The new file realm is added to the table of realms. Follow these steps to manage the realm's users:

  1. Click the MyFileRealm link and then click the Manage Users button.
  2. In the resulting wizard, users are listed/added in the Users table. (This table is empty because we hadn't added any users in the previous procedure.) Click the New button above the Users table to launch the New File Realm User wizard.
  3. For each new user you want to add, specify the user's name (user ID), group (if desired, since it's not mandatory to put users into groups), and password. For this example (see Figure 3), create a user in the SERVLET-USERS group (username MaryJane, password mary2008) in the left pane. In the right pane, create a user in the JSP-USERS group (username TimmyTom, password tom2008). Click OK to add each user.
  4. After you add the users, they're listed in the Users table (see Figure 4).
  5. Restart the Sun Java System Application Server to make sure that the new realm is configured and recognized.

Creating a JDBC Realm in SJSAS

A JDBC realm provides a dynamic environment for managing users and groups, based on a simple database containing two tables: One table stores the users and the other stores the groups. Both tables use the username (ID) as the primary key. The SJSAS knows how to relate the two tables for extracting the corresponding information and accomplishing the authentication phase. SJSAS accepts most of the popular relational database management systems (RDBMS)—PostgreSQL, MySQL, Oracle, DB2, and so on. We chose to use PostgreSQL for this example. Follow these steps to start creating a new JDBC realm:

  1. Use the following SQL statements to create the realm database and the two tables:
    CREATE DATABASE secure
    CREATE TABLE grouptable (USERID VARCHAR(255) NOT NULL, GROUPID VARCHAR(255), PRIMARY KEY (USERID))
    CREATE TABLE usertable (USERID VARCHAR(255) NOT NULL, PASSWORD VARCHAR(255), PRIMARY KEY (USERID))
  2. Populate the tables with a set of users, using the following SQL statements:
    INSERT INTO usertable (USERID, PASSWORD) VALUES ('MarchusRuhl', 'marchus2008')
    INSERT INTO usertable (USERID, PASSWORD) VALUES ('ShawnRay', 'shawn2008')
    INSERT INTO grouptable (USERID, GROUPID) VALUES ('MarchusRuhl', 'SERVLET-USERS')
    INSERT INTO grouptable (USERID, GROUPID) VALUES ('ShawnRay', 'JSP-USERS')

In real life, you would provide a JSP/HTML interface for exposing to users the possibility of creating/deleting accounts in the database. A possible scenario might involve two entity EJBs for the two tables, a persistence.xml to reveal a persistence unit (through JTA, for example), and a stateless EJB that would take care of managing the database (creating/deleting accounts). Developing such a complete application is beyond the scope of this series, but we can provide the main pieces of code (you just have to put them together in a Java EE application). For example, the two entity EJBs might look like Listings 5 and 6.

Listing 5 UserAccount.java.

package ejbs.entities;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "usertable")
public class UserAccount implements java.io.Serializable {

  @Id
  private String userID;

  private String password;

  public UserAccount() {
  }

  public String getUserID() {
    return userID;
  }

  public void setUserID(String userID) {
    this.userID = userID;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}

Listing 6 UserGroup.java.

package ejbs.entities;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "grouptable")
public class UserGroup implements java.io.Serializable {

  @Id
  private String userID;

  private String groupID;

  public UserGroup() {
  }

  public String getUserID() {
    return userID;
  }

  public void setUserID(String userID) {
    this.userID = userID;
  }

  public String getGroupID() {
    return groupID;
  }

  public void setGroupID(String groupID) {
    this.groupID = groupID;
  }
}

The persistence.xml might look like Listing 7.

Listing 7 persistence.xml.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="ManageAccounts" transaction-type="JTA">
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<jta-data-source>auth/jdbc</jta-data-source>
<class>ejbbook.examples.ejbs.entities.UserAccount</class>
<class>ejbbook.examples.ejbs.entities.UserGroup</class>
<properties>
   <!-- <property name="toplink.logging.level" value="INFO"/> -->
   <property name="toplink.target-database" value="PostgreSQL"/>
   <property name="toplink.ddl-generation" value="drop-and-create-tables"/>
   <property name="toplink.application-location" value="{your_app_path}\DDLs\"/>
   <property name="toplink.create-ddl-jdbc-file-name" value="createDDL.sql"/>
   <property name="toplink.drop-ddl-jdbc-file-name" value="dropDDL.sql"/>
   <property name="toplink.ddl-generation.output-mode" value="both"/>
</properties>
</persistence-unit>
</persistence>

Moreover, the stateless EJB may contain a simple method like the following to store users (we're using the MD5 algorithm to encrypt the password, but SHA-256 is also supported):

...
@PersistenceContext(unitName="ManageAccounts")
protected EntityManager manager;
...
public String storeUser(String user_email, String user_password, String user_group) {

  try {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.reset();

    byte[] bytes = md.digest(user_password.getBytes());
    StringBuilder sb = new StringBuilder(2 * bytes.length);
    for (int i = 0; i < bytes.length; i++) {
      int low = (int)(bytes[i] & 0x0f);
      int high = (int)((bytes[i] & 0xf0) >> 4);
      sb.append(HEXADECIMAL[high]);
      sb.append(HEXADECIMAL[low]);
    }

    user_password = sb.toString();

     UserAccount newAccount = new UserAccount();

    newAccount.setUserID(user_email);
     newAccount.setPassword(user_password);

    manager.persist(newAccount);

    if(!user_group.equals("user (no group)"))
      {
      UserGroup userGroup = new UserGroup();

      userGroup.setUserID(user_email);
      userGroup.setGroupID(user_group);

      manager.persist(userGroup);
      }

    return "Success";

    } catch (Exception e)
         { return "Error:" + e.getMessage(); }
  }

At this point, you're ready for more steps:

  1. Start the Sun Java System Application Server and launch the Admin Console (usually the URL is http://localhost:4848/asadmin).
  2. Next, you need to create a connection pool (see Figure 5). Expand the Resources > JDBC node and select the Connection Pool node. In the Pools table, click the New button. Provide a name for the connection pool (for example, AuthPool), a resource type (for example, select javax.sql.DataSource from the drop-down list), and a database vendor (for example, select PostgreSQL from the drop-down list if you have a PostgreSQL distribution installed and ready to go). Click Next.
  3. Now you have to choose some core settings for the connection pool. Most of these settings have default values, which are rarely modified. Your main job here is related to the Properties table (bottom of the page in the Transaction section). In this table, you have to provide important settings for your realm database: database name, RDBMS port, database user and password, etc. Figure 6 shows an example of how to fill in these fields for a PostgreSQL secure database:
  4. After you finish this table of properties, your job is nearly done. Click Finish. Open your new connection pool in the Pools table and click the Ping button at the top of the page to see if the database connection works. Before going further, you must receive a message such as Ping Succeeded.
  5. You're ready to create a JDBC resource. Expand the Resources > JDBC node and select the JDBC Resources node. In the Resources table, click the New button. Provide a Java Naming and Directory Interface (JNDI) name (for example, auth/jdbc) and a connection pool (select AuthPool from the drop-down list). Select the Enabled check box to activate the new JDBC resource (see Figure 7). Click OK.
  6. The next step is to create a JDBC realm based on the JDBC resource. Expand the Configuration > Security node and select the Realm node. In the Realms table, click the New button. Indicate a realm name in the Name field (for example, MyJDBCRealm) and choose the realm class from the Class Name drop-down list (for example, select com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm).
  7. Fill in the rest of the information or use the default settings for the secure database, as shown in Figure 8. (We type none for the digest algorithm because we've provided the user's passwords in simple text; if you want to use a digest algorithm, MD5 and SHA-256 are supported.) When you're finished, click OK to add the new realm to the Realms table.
  8. Restart the Sun Java System Application Server to make sure that the new realm is configured and recognized.

Editing the Certificate Realm

By default, SJSAS defines a certificate realm that supports the SSL authentication mechanism. Later you'll see how to activate the SSL support, but for now it's important to know that this realm populates the SJSAS security context with user data obtained from cryptographically verified client certificates in the keystore (by default, ${com.sun.aas.instanceRoot}/config/keystore.jks) and truststore (by default, ${com.sun.aas.instanceRoot}/config/cacerts.jks) files. In addition, this realm sets up the user identity in the SJSAS security context

Since we're in the development phase, we'll show you how to create a self-signed certificate and how to create/indicate a new keystore and truststore. This is a job for http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html". Follow these steps:

  1. Create the keystore (our keystore name is mykeystore.jks and it's placed in the ${com.sun.aas.instanceRoot}/config folder). Open a command prompt and point to the ${com.sun.aas.instanceRoot}/config folder. Run the following keytool statement:
    keytool –genkey –alias s1as –keyalg RSA –keypass changeit –storepass changeit –keystore mykeystore.jks

    When you press Enter, keytool prompts you to enter the first and last name, organizational unit, organization, locality, state, and country code. For the first and last name, type the server name. In our case, this is localhost.

  2. Export the generated server certificate in mykeystore.jks into the file myserver.cer:
    keytool –export –alias s1as –storepass changeit –file myserver.cer –keystore mykeystore.jks
  3. Create a truststore named mycacerts.jks and add the server certificate (myserver.cer) to it:
    keytool –import –v –trustcacerts –alias s1as –file myserver.cer –keystore mykeystore.jks –keypass changeit
    –storepass changeit
  4. When you press Enter, you'll see a list of details about the certificate. Based on these details, you have to decide whether the certificate is a trust certificate. Obviously, we have to accept the certificate as trusted, so type yes to this question and press Enter.
  5. Our certificate is ready to use in the development phase. If you want to go further, in the production phase, than you have to obtain digitally signed certificate from a certificate authority.

Now we have to indicate to the SJSAS to use mykeystore.jks instead of keystore.jks, and mycacerts.jks instead of cacerts.jks. Follow these steps:

  1. Start the SJSAS, launch the Admin Console (usually the URL is http://localhost:4848/asadmin), and log into the Admin Console.
  2. Click the Application Server node.
  3. Switch to the JVM Settings tab.
  4. Switch to the JVM Options tab.
  5. Find the keystore property:
    -Djavax.net.ssl.keyStore=${com.sun.aas.instanceRoot}/config/keystore.jks
  6. Modify the property as follows:
    -Djavax.net.ssl.keyStore=${com.sun.aas.instanceRoot}/config/mykeystore.jks
  7. Find the truststore property:
    -Djavax.net.ssl.trustStore=${com.sun.aas.instanceRoot}/config/cacerts.jks
  8. Modify the property as follows:
    -Djavax.net.ssl.trustStore=${com.sun.aas.instanceRoot}/config/mycacerts.jks
  9. Click Save.
  10. Restart the Sun Java System Application Server to make sure that the modifications are added and recognized.

Creating a New Certificate Realm

Follow these steps to create a new certificate realm:

  1. Expand the Configuration > Security node and select the Realm node.
  2. In the Realms table, click the New button.
  3. In the New Realm wizard, provide a name for this realm (for example, MyCertificateRealm) and select its corresponding class:
com.sun.enterprise.security.auth.realm.certificate.CertificateRealm
  1. (Optional) If desired, assign a group to this realm and/or specify a list of additional properties in the Additional Properties table.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020