星期三, 二月 25, 2004

jaas解决JAAS多次login

Re: [jBoss-User] jaas
In your case the client of JBoss is a multi-threaded server where the identity of a
client
can change with each servlet request. I have added a configuration option to the
ClientLoginModule that allows you to put it in the mode where it uses thread local
storage for the principal and credentials that are established during a login.
Configure the module with the multi-threaded option set to true as here:
other {
// Put your login modules that work without jBoss here

// jBoss LoginModule
org.jboss.security.ClientLoginModule required multi-threaded=true;

// Put your login modules that need jBoss here
};

and then in your servlet request handler you need to establish the client identity:

protected void doRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String username = ...; // Obtain username & password from request properties
char[] password = ...;
LoginContext lc = null;
try
{
lc = new LoginContext("other", new CallbackHandler()
{
public void handle(Callback[] callbacks) throws
IOException, ServletException
{
for(int i = 0; i < callbacks.length; i++)
{
if (callbacks[i] instanceof NameCallback)
{
NameCallback n = (NameCallback) callbacks[i];
n.setName(username);
}
else if(callbacks[i] instanceof PasswordCallback)
{
PasswordCallback p = (PasswordCallback) callbacks[i];
p.setPassword(password);
}
else
{
throw new ServletException("Unrecognized Callback:
"+callbacks[i]);
}
}
}
}
);
lc.login();
// Work as username...
}
catch(LoginException e)
{
throw new ServletException(e.getMessage());
}
finally
{
if( lc != null )
lc.logout();
}
}

You could also just use the SecurityAssociation class directly:

import org.jboss.security.SecurityAssociation;

public void init(ServletConfig config) throws ServletException
{ // Use thread local storage for username,password
SecurityAssociation.setServer();
}
protected void doRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String username = ...; // Obtain username & password from request properties
char[] password = ...;
try
{
SecurityAssociation.setPrincipal(new SimplePrincipal(username));
SecurityAssociation.setCredential(password);
// Work as username...
}
finally
{
SecurityAssociation.setPrincipal(null);
SecurityAssociation.setCredential(null);
}
}
害怕丢了,放到自己包里比较安心。:D