JAAS,Java Authentication and Authorization Service,Java认证和授权服务。“认证”部分主要负责确定程序使用者的身份,而“授权”将各个用户映射到相应的权限。下面通过java核心技术上的例子来记录JAAS的执行流程。大体执行流程如下图:
首先,JAASTest代码如下:
JButton getValueButton = new JButton("Get Value");
getValueButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
getValue();
}
});
public void getValue()
{
try
{
LoginContext context = new LoginContext("Login1", new SimpleCallbackHandler(username
.getText(), password.getPassword()));
context.login();
Subject subject = context.getSubject();
propertyValue.setText(""
+ Subject.doAsPrivileged(subject, new SysPropAction(propertyName.getText()), null));
context.logout();
}
catch (LoginException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
获取到用户输入的username和password,构造SimpleCallbackHandler对象,传递到登陆控制上下文中LoginContext。
LoginContext代码如下:
public LoginContext(String name, CallbackHandler callbackHandler)
throws LoginException {
init(name);
if (callbackHandler == null)
throw new LoginException(Resou