Monday, March 10, 2008
JAAS Callback Example
JAAS已經有內建讓你從console或是跳出一個GUI視窗讓使用者填入帳號密碼進行Authentication的功能了
如果你想要有其他種方式
就必須去實作CallbackHandler這個interface
下面我提供一個只有兩個類別、一個設定檔的範例給大家參考
SampleLoginModule.java
import java.util.Map;
import java.util.Arrays;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
public class SampleLoginModule implements LoginModule {
private Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
}
public boolean login() throws LoginException {
if (callbackHandler == null)
throw new LoginException("Error: no CallbackHandler");
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("user name: ");
callbacks[1] = new PasswordCallback("password: ", true);
try {
callbackHandler.handle(callbacks);
} catch (Exception e) {
e.printStackTrace();
}
String username = ((NameCallback) callbacks[0]).getName();
char[] password = ((PasswordCallback) callbacks[1]).getPassword();
System.out.println("Username: " + username);
System.out.println("Password: " + Arrays.toString(password));
return true;
}
public boolean commit() throws LoginException {
return true;
}
public boolean abort() throws LoginException {
return true;
}
public boolean logout() throws LoginException {
return true;
}
}
Test.java
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;
import com.sun.security.auth.callback.DialogCallbackHandler;
import com.sun.security.auth.callback.TextCallbackHandler;
public class Test {
public static void main(String[] args) throws Exception {
CallbackHandler textCallbackHandler = new TextCallbackHandler();
CallbackHandler dialogCllbackHandler = new DialogCallbackHandler();
// LoginContext lc = new LoginContext("Sample", textCallbackHandler);
LoginContext lc = new LoginContext("Sample", dialogCllbackHandler);
lc.login();
}
}
sample_jaas.config
Sample {
SampleLoginModule required;
};
放在同一個目錄中
執行
javac *.java
java -Djava.security.auth.login.config=sample_jaas.config Test
就可以跑跑看啦!
延伸閱讀
Labels: authentication, code, example, JAAS, java