Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Writing a Custom JAAS LoginModule to Support Secure DataBase Authentication

Writing a Custom JAAS LoginModule to Support Secure DataBase Authentication

With the arrival of BEA WebLogic Server 7.0, a new security architecture with improved and expanded security features was introduced. The primary goal of that new architecture is to let you plug in security providers from different security vendors and to let them cooperate seamlessly with your J2EE applications.

A security provider is a module that handles some specific security tasks, like authentication and authorization. However, instead of buying a security provider you can develop your own. When there are no third-party providers that meet your security needs, this can be your only effective solution. I ran into this situation when I needed to authenticate users based on information in a relational database. Since there was no standard WebLogic provider that did the job, and no suitable third-party alternative, I decided to develop my own database authentication-provider. In fact, it wasn't that difficult, as I will show you in this article.

Authentication in WebLogic
Authentication is probably the most important part of security. It is the process that proves the identity of a user based on some credentials, in most cases a password. The default WebLogic 7 authentication provider uses an embedded LDAP server to store users and groups as a replacement of the well-known file realm in WebLogic 6. In addition, WebLogic 7 provides a set of LDAP authentication providers for accessing external LDAP stores like OpenLDAP or iPlanet. And what happened with the RDBMS security realm that was present in WebLogic 6? Well, it is still possible to use the RDBMS security realm, but you will have to boot WebLogic Server in so called "compatibility mode," meaning that the server provides backward compatibility with the WebLogic 6.x security realms by using a special kind of authentication provider: a realm adapter authentication provider. However, the use of these realm adapter providers is deprecated; hence, to make your projects future-proof it's better to use an authentication provider that fits into WebLogic's new security architecture.

Secure Passwords
Prior to guiding you through the different steps in developing your own authentication provider, it's important to discuss how you can use a relational database as an authentication information store with the help of encryption. After all, the most important part is the storage of passwords. Storing these passwords in plain text in the database isn't the right way to go. It's better to obscure the passwords with a messagedigest algorithm. A messagedigest is a secure, one-way hash function: a function that calculates a fixed-length hash value of an arbitrary-sized original value and can be computed only one way. Once the algorithm has been applied to the password, it's impossible to go backwards and find the original password - viewing the messagedigest alone will not reveal the contents of the original message and changing even a single bit on the message will result in a totally different output value. The only way is to pass in random input until you get the original password - a brute-force attack. Your authentication provider doesn't need to know the original passwords at all - it only needs to apply the hash function on any password given by a user and compare it with the stored hashed password of that user. If both are the same, the user supplied the correct password and can be authenticated.

Putting the Messagedigest to Work
In Java there's an easy way to calculate messagedigests by using the java.security.MessageDigest class. The following code snippet shows you how to apply an MD5 messagedigest algorithm (a 128-bit digest) on a password string:

MessageDigest md =
MessageDigest.getInstance("MD5");
md.update(originalPwd.getBytes());
byte[] digestedPwdBytes = md.digest();

Messagedigests are also used to create a checksum, a unique ID for a piece of text (also called a digital fingerprint). This is what happens if you sign a jar file: a checksum is calculated from the contents of the JAR file, encrypted, and stored in the manifest.mf file in base64 encryted format. Base64 is a way to encode arbitrary binary data so that the result contains only printable characters (note that base64-encoded data takes one-third more space than the data before conversion). Since the messagedigest algorithm outputs its response as a byte array, we can use base64 encoding to transform the hash bytes into a string so that we can store it in a varchar field in the database. There are many base64 encoders available, but the easiest way is to use the one that's included in the weblogic.jar library: weblogic.apache.xerces.utils.Base64. The use of this class is trivial, as shown in the next code sample:

String digestedPwdString =
new String(Base64.encode(digestedPwdBytes));

Security Provider Architecture
Now let's go back to the Authentication provider itself. As I mentioned before, an Authentication provider is one kind of security provider in WebLogic 7.0. To understand the structure of an Authentication provider, it's important to discuss the general architecture of all security providers. Each provider is a module that can be plugged into a security realm. It is developed by implementing the appropriate security service provider interfaces (SSPIs) from the weblogic.security.spi package and by creating an MDF file to generate an MBean type used to configure and manage the provider (see Figure 1).

MBeans, or Managed Beans, are a construct of JMX, the Java Management eXtensions package. JMX provides support for application and network management in Java. An MBean is a specific type of JavaBean that can be managed in a JMX-compliant application. In WebLogic, MBean types are created by the WebLogic MBeanMaker utility on the basis of an MBean Definition File (MDF), an XML file that describes the MBean type. This XML file consists of properties used to configure the security provider, e.g., name, description, and implementation classes. These properties can be exposed in the server's administration console, where you can view and edit them.

JAAS for Authentication
In developing my own authentication provider, the sample security providers on BEA's dev2dev site turned out to be very useful. I used them as a starting point to work out my database authentication provider and I recommend that you take a close look at them if you are planning to do some security provider development yourself. If you look at the sample authentication provider, you will see the use of the Java Authentication and Authorization Service (JAAS) in the provider's implementation classes. WebLogic uses JAAS internally for authentication as well as for remote fat-client authentication. The authentication provider authenticates users in a JAAS loginmodule (javax.security.auth.spi.LoginModule). Each authentication provider needs to have exactly one LoginModule, but you can configure multiple Authentication providers in one security realm. This way you have multiple LoginModules that can perform different kinds of authentication for a user. The authentication mechanism itself is based on users and groups: a user represents a person, a group represents a category of persons. After authentication, WebLogic assigns a principal to both users and groups. The principals are stored in a JAAS subject during the commit() method of the loginmodule. Any principal that is going to represent a WebLogic Server user or group needs to implement the WLSUser or WLSGroup interface. The sample Authentication provider on dev2dev uses the weblogic.security.principal.WLSUserImpl to represent the user into a subject, and the weblogic.security.principal.WLSGroupImpl to represent the groups that contain the user. That's sufficient for the database provider too, so you can reuse the same mechanism.

Closer Look at the LoginModule
The only things you need to change in the sample loginmodule are the details in checking the correctness of username and password in the login() method. Obviously the security framework calls this method when a user has to be authenticated. Authentication has to be proven here by checking the user's password. The sample Authentication provider delegates to the SampleAuthenticatorDatabase class to retrieve user and group information from a persistent store - in this case, a plain text file. You have to do two things. The first one is changing the password check in the login() method. Remember that you should store a hash value of the password, so instead of checking if a given password matches the password in the database, you should apply the messagedigest algorithm on the given password first, and then compare it with the stored hash value. Second, you have to adapt the SampleAuthenticatorDatabase (or better, use your own class like RDBMSAuthenticatorDatabase) to retrieve user and group info from a relational database instead of a text file. If you don't need hierarchical roles, it's sufficient to create two simple tables in the database:

CREATE TABLE Principals
(principalId varchar(50), password var char(25));
CREATE TABLE Roles
(principalId varchar(50), role varchar(50));

Next you need to add some simple database access code in the authenticator's database class. However, there's a snake in the grass here: since WebLogic uses the Authentication provider to also authenticate the user that boots the server, you can't use a javax.sql.DataSource as the factory for database connection objects because the naming service isn't started yet. You have to use a DriverManager to obtain a connection to the database. Once the server is started, it's no problem to use a DataSource, and you should probably do it at that time to benefit from connection pooling.

Implement the SSPI
The last Java class you have to write is the implementation of the weblogic.security.spi.AuthenticationProvider SSPI. This class represents the runtime implementation of the authentication provider. Here you need to specify the authenticator's database and LoginModule implementation classes. For the SampleAuthenticationProviderImpl, these are SampleLoginModule and SampleAuthenticatorDatabase. Obviously you need to change these into your own classnames. After successful authentication, a principal validation provider is needed to sign the principals and ensure their authenticity between programmatic server invocations. The SampleAuthenticationProviderImpl reuses the standard WebLogic principal validator for this purpose, and that's sufficient for the database authentication provider too.

Configuration and Deployment
That's all for the Java classes. The last thing you need is the MDF file. Again, you can easily adapt the SampleAuthenticator.xml file and supply some additional properties as <MBeanAttribute> tags, e.g., database URL, drivername, username, password, query to retrieve principal info, query to retrieve role info. The MBean that is generated from this MDF has to be supplied as an argument in the constructor of the authenticator's database class, so you can use the properties of the MBean to configure the class. The next step is to generate the MBean using WebLogic's MBeanMaker. The sample security provider's archive contains example ANT scripts showing you how to do this with the weblogic.management.commo.WebLogicMBeanMaker class. The same class is used to build the authentication provider's MJF file (MBean Jar File). Finally, you need to copy that Java archive into the /lib/mbeantypes directory relative to the home dir of your WebLogic Server installation. After a reboot of the server, you can install the authentication provider by navigating in the admin console to Security - Realms - <yourRealm> - Providers - Authentication Providers. The name of the newly created provider should be visible now, e.g. "configure new RDBMS Authenticator" (see Figure 2). Set the right properties and reboot the server. This will activate the authentication provider. Remember that WebLogic uses it immediately upon booting up the server, so make sure there's a user in the Administrator's role present in your database or else you won't be able to start the server.

Conclusion
Although primarily intended as a framework to plug in third-party security providers, WebLogic's new security architecture can be used to develop your own custom security provider too. It's not that hard to create, deploy, and configure your own authentication provider, as I've demonstrated in this article. Basic knowledge of JAAS and JMX, some good samples, and a bit of encryption magic is all you need. The last thing is perhaps the most important, because even the best authentication provider turns out to be worthless when combined with an insecure authentication store.

Resources

  • BEA WebLogic Server 7.0 Security Web site: http://edocs.bea.com/wls/docs70/security.html
  • BEA dev2dev code direct: WebLogic 7.0.1 Sample Security Providers download: http://dev2dev.bea.com/code/codedirect.jsp
  • Java Management Extensions home page: http://java.sun.com/products/JavaManagement
  • Java Authentication and Authorization Service home page: http://java.sun.com/products/jaas
  • More Stories By Tim Pijpops

    I am presently working as a Software Architect for Egova, a Belgian company specialized in e-government projects. My duties include architecting and designing J2EE solutions. I am particularly interested in J2EE, Web Services, Security and Business Intelligence. I own a Master's degree in Informatics.

    Comments (3)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    @ThingsExpo Stories
    BnkToTheFuture.com is the largest online investment platform for investing in FinTech, Bitcoin and Blockchain companies. We believe the future of finance looks very different from the past and we aim to invest and provide trading opportunities for qualifying investors that want to build a portfolio in the sector in compliance with international financial regulations.
    A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
    Imagine if you will, a retail floor so densely packed with sensors that they can pick up the movements of insects scurrying across a store aisle. Or a component of a piece of factory equipment so well-instrumented that its digital twin provides resolution down to the micrometer.
    In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settle...
    Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
    Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
    Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
    Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
    In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
    "IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
    When shopping for a new data processing platform for IoT solutions, many development teams want to be able to test-drive options before making a choice. Yet when evaluating an IoT solution, it’s simply not feasible to do so at scale with physical devices. Building a sensor simulator is the next best choice; however, generating a realistic simulation at very high TPS with ease of configurability is a formidable challenge. When dealing with multiple application or transport protocols, you would be...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    We are given a desktop platform with Java 8 or Java 9 installed and seek to find a way to deploy high-performance Java applications that use Java 3D and/or Jogl without having to run an installer. We are subject to the constraint that the applications be signed and deployed so that they can be run in a trusted environment (i.e., outside of the sandbox). Further, we seek to do this in a way that does not depend on bundling a JRE with our applications, as this makes downloads and installations rat...
    Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
    DX World EXPO, LLC, a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
    In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
    Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
    "Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
    The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...