Acegi 使用笔记
[简介]
Acegi Security System 是一种功能强大并易于使用的替代性方案,使您不必再为 Java 企业应用程序编写大量的安全代码。虽然它专门针对使用 Spring 框架编写的应用程序,但是任何类型的 Java 应用程序都没有理由不去使用 Acegi。
?
Acegi Security System 使用安全过滤器来提供企业应用程序的身份验证和授权服务。该框架提供了不同类型的过滤器,可以根据应用程序的需求进行配置。您将在本文后面了解到 安全过滤器的不同类型;现在,只需注意可以为如下任务配置 Acegi 安全过滤器:
正如这个列表显示的那样,Acegi 的安全过滤器允许您执行保护企业应用程序所需的几乎任何事情。
?
?
[基础工作]
在你的Web应用的lib中添加Acegi下载包中的acegi-security.jar
?
[web.xml]
在web.xml配置
?[JdbcDaoImpl.java]
?
public class JdbcDaoImpl extends org.acegisecurity.userdetails.jdbc.JdbcDaoImpl {private String anonymousRoleName = "ROLE_ANONYMOUS";private Log logger = LogFactory.getLog(JdbcDaoImpl.class);private PreparedStatement userPstmt;private PreparedStatement rolePstmt;public UserDetails loadUserByUsername(String userName)throws UsernameNotFoundException, DataAccessException {UserDetails user = findUserByName(userName);if (user == null) {throw new UsernameNotFoundException("User not found");}return user;}private UserDetails findUserByName(String userName) {Connection connection = null;ResultSet rsUser = null;ResultSet rsRole = null;UserDetails user = null;String logonName = null;String password = null;String roleName = null;int status = -1;boolean enabled = false;Vector roles = null;GrantedAuthority[] rolesArray = null;try {connection = getDataSource().getConnection();userPstmt = connection.prepareStatement("select * from users where user_NAME=?");userPstmt.setString(1, userName);rsUser = userPstmt.executeQuery();if (rsUser.next()) {logonName = rsUser.getString("USER_NAME");password = rsUser.getString("PASSWORD");status = rsUser.getInt("STATUS");if (status == 1)enabled = true;} else {return null;}rolePstmt = connection.prepareStatement("SELECT ROLE.NAME Role FROM ROLE, users_ROLES, users WHERE ROLE.ID= user_ROLES.FK_ROLES and users.user_NAME=?");rolePstmt.setString(1, userName);rsRole = rolePstmt.executeQuery();roles = new Vector();while (rsRole.next()) {roleName = getRolePrefix() + rsRole.getString("Role");roles.add(new GrantedAuthorityImpl(roleName));}rolesArray = new GrantedAuthority[roles.size() + 1];int index = 0;for (index = 0; index < roles.size(); index++)rolesArray[index] = (GrantedAuthority) roles.get(index);rolesArray[index] = new GrantedAuthorityImpl(anonymousRoleName);user = new User(logonName, password, enabled, true, true, true,rolesArray);} catch (SQLException e) {logger.fatal("", e);} finally {try {//关闭数据库连接的程序} catch (SQLException sqlx) {logger.fatal("", sqlx);} catch (NullPointerException x) {logger.fatal("", x);}}return user;}}