星期二, 二月 24, 2004

JBOSS使用JAAS框架来验证用户代码及配置(2)

JavaRanch Big Moose Saloon: JAAS With JBOSS: My How-To Tutorial

//THE IMPORTS
import org.jboss.security.auth.callback.SecurityAssociationHandler;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import java.security.Principal;
//LOGIN CODE
//Note: Login before you get initial context
try{
SecurityAssociationHandler handler = new SecurityAssociationHandler();
//PRINCIPAL TO LOGIN WITH
/*
* To make this work, you'll need to create a user with this name
* in your security file or database or whatever you use. I use a database
* to store them. For this example, we'll use user="Robert", password="Paris"
*
* Note: I am creating a new Principal subclass here because Principal is
* an abstract class.
*/
Principal userPrincipal = new Principal()
{ //THIS IS ALL YOU NEED TO IMPLEMENT
public String getName()
{ return "Robert";
}
};
//SET SECURITY ASSOCIATION HANDLER-SPECIFIC SETTINGS
//Syntax: setSecurityInfo( Principal , char[] );
handler.setSecurityinfo( userPrincipal, "Paris".toCharArray() );
//GET LOGIN CONTEXT (NOTE: EJBSecurityDomain is the name I gave it in descriptor)
LoginContext loginContext = new LoginContext( "EJBSecurityDomain", ( CallbackHandler ) handler );
//LOGIN
loginContext.login();
}catch (Exception e)
{ e.printStackTrace();}
//THEN DO ALL YOUR getInitialContext STUFF HERE