Subject: JAAS framework is a perfect example of Strategy Design Pattern
Author: authen
In response to: Inject your own login module into JAAS framework -- Put all pieces together
Posted on: 12/18/2013 08:47:04 PM
The strategy pattern is a behavioral design pattern. In the strategy pattern, different behaviors are represented as Concrete Strategy classes and they share a common Strategy interface. A Context class contains a reference to the common Strategy interface. By changing the Context's Strategy, different behaviors can be obtained.
+-------------+ +------------+
| Context |* -------------->| Strategy |
+-------------+ +------------+
| # logic() | | # hook(); |
+-------------+ +------------+
^
|
----------------------
| |
+------------+ +------------+
| Strategy1 | | Strategy2 |
+------------+ +------------+
| # hook() | | # hook() |
+------------+ +------------+
The strategy pattern is based on separation principle (in contrast to unification principle as in subclass inheritance) where Strategy specifying hook methods is defined on one side and business logic and user's data are processed inside Context on the other side (with help, for sure, for calling hook methods).
Here,
LoginContext serves as business logic
Context and
LoginModule serves as
Strategy interface. With different input as to strategy "myLoginEntity" and user's data "CallBack", different authentication behavior can be achieved.
>
> On 10/20/2012 01:00:32 AM
authen wrote:
Now that you have your own login module ready, you can integrate it into your business layer with the help of configuration file named C:\temp\jaas_login.conf:
myLoginEntity {
com.myCompany.MyLoginModule required
anonymousAllowed=true
debug=true;
};
Integration:
public static void main(String[] args) throws Exception
{
System.setProperty("java.security.auth.login.config",
"C:\\temp\\jaas_login.conf");
try{
// CallbackHandler
final String name = "Joe";
final String password = "Joe";
CallbackHandler ch = new CallbackHandler(){
public void handle (Callback[] callbacks) throws
UnsupportedCallbackException, IOException
{
for(int j=0; j<callbacks.length; j++) {
Callback callBack = callbacks[j];
// Handles username callback.
if (callBack instanceof NameCallback) {
NameCallback nc = (NameCallback)callBack;
nc.setName(name);
// Handles password callback.
} else if (callBack instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback)callBack;
pc.setPassword(password.toCharArray());
} else {
throw new UnsupportedCallbackException(callBack,
"Call back not supported");
}
}
}
};
LoginContext lc = new LoginContext("myLoginEntity", ch);
lc.login();
Subject subject = lc.getSubject();
System.out.println(subject);
}catch(Exception e){
e.printStackTrace();
}
}
Here is the output:
My Login Module - Constructor called
My Login Module - initialize() called
My Login Module - login() called
Succeeded!
My Login Module - commit() called
Subject:
Principal: Joe
References: