spring security以前叫acegi是一个非常棒的权限管理框架,下面介绍一下如何配置:
1.导入jar包,见附件;
2.web.xml中添加
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.applicationContext_security.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!--不过滤css、js、图片等 -->
<http pattern="/css/**" security="none"/>
<http pattern="/img/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/**" access-denied-page="/404.jsp">
<intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/user/**" access="ROLE_ADMIN"/>
<remember-me/>
<form-login login-page="/login.html" default-target-url="/index.html"/>
<logout logout-url="/logout" logout-success-url="/login.html"/>
<session-management invalid-session-url="/login.html" session-authentication-error-url="/login.html"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="myJdbcDaoImpl">
<!--密码MD5加密,用户名做盐值 -->
<password-encoder hash="md5">
<salt-source user-property="username"/>
</password-encoder>
</authentication-provider>
</authentication-manager>
<!--重写JdbcDaoImpl -->
<beans:bean id="myJdbcDaoImpl" class="cn.investide.security.MyJdbcDaoImpl">
<beans:property name="dataSource" ref="dataSource"></beans:property>
</beans:bean>
</beans:beans>
MyJdbcDaoImpl内容如下:
public class MyJdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {
//根据你的数据库修改sql语句
public static final String DEF_USERS_BY_USERNAME_QUERY = "select user_id,username,real_name,password,enabled from users WHERE username = ? ";
public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select u.username,a.authority_name as authorities "
+ "from authority a,users u,user_role_mapping ur,role_authority_mapping ra "
+ "where u.user_id=ur.user_id "
+ "and ur.role_id=ra.role_id "
+ "and ra.authority_id=a.authority_id and username=? ";
public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.id, g.group_name, ga.authority "
+ "from groups g, group_members gm, group_authorities ga "
+ "where gm.username = ? "
+ "and g.id = ga.group_id "
+ "and g.id = gm.group_id";
protected MessageSourceAccessor messages = SpringSecurityMessageSource
.getAccessor();
private String authoritiesByUsernameQuery;
private String groupAuthoritiesByUsernameQuery;
private String usersByUsernameQuery;
private String rolePrefix = "";
private boolean usernameBasedPrimaryKey = true;
private boolean enableAuthorities = true;
private boolean enableGroups
public MyJdbcDaoImpl() {
usersByUsernameQuery = DEF_USERS_BY_USERNAME_QUERY;
authoritiesByUsernameQuery = DEF_AUTHORITIES_BY_USERNAME_QUERY;
groupAuthoritiesByUsernameQuery = DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY;
}
protected void addCustomAuthorities(String username,
List<GrantedAuthority> authorities) {
}
public String getUsersByUsernameQuery() {
return usersByUsernameQuery;
}
protected void initDao() throws ApplicationContextException {
Assert.isTrue(enableAuthorities || enableGroups,
"Use of either authorities or groups must be enabled");
}
public MyUserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
List<UserDetails> users = loadUsersByUsername(username);
if (users.size() == 0) {
logger.debug("Query returned no results for user '" + username
+ "'");
throw new UsernameNotFoundException(messages.getMessage(
"JdbcDaoImpl.notFound", new Object[] { username },
"Username {0} not found"), username);
}
UserDetails user = users.get(0); // contains no GrantedAuthority[]
Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();
if (enableAuthorities) {
dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));
}
if (enableGroups) {
dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));
}
List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(
dbAuthsSet);
addCustomAuthorities(user.getUsername(), dbAuths);
if (dbAuths.size() == 0) {
logger.debug("User '" + username
+ "' has no authorities and will be treated as 'not found'");
throw new UsernameNotFoundException(messages.getMessage(
"JdbcDaoImpl.noAuthority", new Object[] { username },
"User {0} has no GrantedAuthority"), username);
}
return createUserDetails(username, (MyUserDetails) user, dbAuths);
}
protected List<UserDetails> loadUsersByUsername(String username) {
return getJdbcTemplate().query(usersByUsernameQuery,
new String[] { username }, new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum)
throws SQLException {
int userId = rs.getInt(1);
String username = rs.getString(2);
String realname = rs.getString(3);
String password = rs.getString(4);
boolean enabled = rs.getBoolean(5);
UserDetails myUser = new MyUser(userId, username,realname,
password, enabled, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
return myUser;
}
});
}
protected List<GrantedAuthority> loadUserAuthorities(String username) {
return getJdbcTemplate().query(authoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum)
throws SQLException {
String roleName = rolePrefix + rs.getString(2);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(
roleName);
return authority;
}
});
}
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery,
new String[] { username }, new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum)
throws SQLException {
String roleName = getRolePrefix() + rs.getString(3);
GrantedAuthorityImpl authority = new GrantedAuthorityImpl(
roleName);
return authority;
}
});
}
protected MyUserDetails createUserDetails(String username,
MyUserDetails userFromUserQuery,
List<GrantedAuthority> combinedAuthorities) {
int returnUserId = userFromUserQuery.getUserId();
String returnUsername = userFromUserQuery.getUsername();
String returnRealname = userFromUserQuery.getRealname();
if (!usernameBasedPrimaryKey) {
returnUsername = username;
}
MyUserDetails myUser = new MyUser(returnUserId, returnUsername, returnRealname,
userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),
true, true, true, combinedAuthorities);
return myUser;
}
public void setAuthoritiesByUsernameQuery(String queryString) {
authoritiesByUsernameQuery = queryString;
}
protected String getAuthoritiesByUsernameQuery() {
return authoritiesByUsernameQuery;
}
public void setGroupAuthoritiesByUsernameQuery(String queryString) {
groupAuthoritiesByUsernameQuery = queryString;
}
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
protected String getRolePrefix() {
return rolePrefix;
}
public void setUsernameBasedPrimaryKey(boolean usernameBasedPrimaryKey) {
this.usernameBasedPrimaryKey = usernameBasedPrimaryKey;
}
protected boolean isUsernameBasedPrimaryKey() {
return usernameBasedPrimaryKey;
}
public void setUsersByUsernameQuery(String usersByUsernameQueryString) {
this.usersByUsernameQuery = usersByUsernameQueryString;
}
protected boolean getEnableAuthorities() {
return enableAuthorities;
}
public void setEnableAuthorities(boolean enableAuthorities) {
this.enableAuthorities = enableAuthorities;
}
protected boolean getEnableGroups() {
return enableGroups;
}
public void setEnableGroups(boolean enableGroups) {
this.enableGroups = enableGroups;
}
}
注意,以上源码中我自己增加了userId
扩展MyUserDetails
public interface MyUserDetails extends Serializable,UserDetails{
// ~ Methods
// ========================================================================================================
int getUserId();
/**
* Returns the authorities granted to the user. Cannot return
* <code>null</code>.
*
* @return the authorities, sorted by natural key (never <code>null</code>)
*/
Collection<GrantedAuthority> getAuthorities();
/**
* Returns the password used to authenticate the user. Cannot return
* <code>null</code>.
*
* @return the password (never <code>null</code>)
*/
String getPassword();
/**
* Returns the username used to authenticate the user. Cannot return
* <code>null</code>.
*
* @return the username (never <code>null</code>)
*/
String getUsername();
String getRealname();
/**
* Indicates whether the user's account has expired. An expired account
* cannot be authenticated.
*
* @return <code>true</code> if the user's account is valid (ie
* non-expired), <code>false</code> if no longer valid (ie expired)
*/
boolean isAccountNonExpired();
/**
* Indicates whether the user is locked or unlocked. A locked user cannot be
* authenticated.
*
* @return <code>true</code> if the user is not locked, <code>false</code>
* otherwise
*/
boolean isAccountNonLocked();
/**
* Indicates whether the user's credentials (password) has expired. Expired
* credentials prevent authentication.
*
* @return <code>true</code> if the user's credentials are valid (ie
* non-expired), <code>false</code> if no longer valid (ie expired)
*/
boolean isCredentialsNonExpired();
/**
* Indicates whether the user is enabled or disabled. A disabled user cannot
* be authenticated.
*
* @return <code>true</code> if the user is enabled, <code>false</code>
* otherwise
*/
boolean isEnabled();
}
扩展MyUser
public class MyUser implements MyUserDetails, CredentialsContainer {
// ~ Instance fields
// ================================================================================================
private int userId;
private String password;
private final String username;
private final String realname;
private final Set<GrantedAuthority> authorities;
private final boolean accountNonExpired;
private final boolean accountNonLocked;
private final boolean credentialsNonExpired;
private final boolean enabled;
// ~ Constructors
// ===================================================================================================
/**
* @deprecated
*/
public MyUser(int userId, String username,String realname, String password,
boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
GrantedAuthority[] authorities) {
this(userId, username, realname, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked,
authorities == null ? null : Arrays.asList(authorities));
}
/**
* Construct the <code>User</code> with the details required by
* {@link org.springframework.security.authentication.dao.DaoAuthenticationProvider}
* .
*
* @param username
* the username presented to the
* <code>DaoAuthenticationProvider</code>
* @param password
* the password that should be presented to the
* <code>DaoAuthenticationProvider</code>
* @param enabled
* set to <code>true</code> if the user is enabled
* @param accountNonExpired
* set to <code>true</code> if the account has not expired
* @param credentialsNonExpired
* set to <code>true</code> if the credentials have not expired
* @param accountNonLocked
* set to <code>true</code> if the account is not locked
* @param authorities
* the authorities that should be granted to the caller if they
* presented the correct username and password and the user is
* enabled. Not null.
*
* @throws IllegalArgumentException
* if a <code>null</code> value was passed either as a parameter
* or as an element in the <code>GrantedAuthority</code>
* collection
*/
public MyUser(int userId, String username, String realname, String password,
boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
if (((username == null) || "".equals(username)) || (password == null)) {
throw new IllegalArgumentException(
"Cannot pass null or empty values to constructor");
}
this.userId = userId;
this.username = username;
this.realname = realname;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections
.unmodifiableSet(sortAuthorities(authorities));
}
// ~ Methods
// ========================================================================================================
public Collection<GrantedAuthority> getAuthorities() {
return authorities;
}
public String getPassword() {
return password;
}
public int getUserId() {
return userId;
}
public String getUsername() {
return username;
}
public String getRealname() {
return realname;
}
public boolean isEnabled() {
return enabled;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void eraseCredentials() {
password = null;
}
private static SortedSet<GrantedAuthority> sortAuthorities(
Collection<? extends GrantedAuthority> authorities) {
Assert.notNull(authorities,
"Cannot pass a null GrantedAuthority collection");
// Ensure array iteration order is predictable (as per
// UserDetails.getAuthorities() contract and SEC-717)
SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(
new AuthorityComparator());
for (GrantedAuthority grantedAuthority : authorities) {
Assert.notNull(grantedAuthority,
"GrantedAuthority list cannot contain any null elements");
sortedAuthorities.add(grantedAuthority);
}
return sortedAuthorities;
}
private static class AuthorityComparator implements
Comparator<GrantedAuthority>, Serializable {
public int compare(GrantedAuthority g1, GrantedAuthority g2) {
// Neither should ever be null as each entry is checked before
// adding it to the set.
// If the authority is null, it is a custom authority and should
// precede others.
if (g2.getAuthority() == null) {
return -1;
}
if (g1.getAuthority() == null) {
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
}
/**
* Returns {@code true} if the supplied object is a {@code User} instance
* with the same {@code username} value.
* <p>
* In other words, the objects are equal if they have the same username,
* representing the same principal.
*/
public boolean equals(Object rhs) {
if (rhs instanceof MyUser) {
return username.equals(((MyUser) rhs).username);
}
return false;
}
/**
* Returns the hashcode of the {@code username}.
*/
public int hashCode() {
return username.hashCode();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("UserId: ").append(this.userId).append("; ");
sb.append("Username: ").append(this.username).append("; ");
sb.append("Realname: ").append(this.realname).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").append(this.enabled).append("; ");
sb.append("AccountNonExpired: ").append(this.accountNonExpired)
.append("; ");
sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired)
.append("; ");
sb.append("AccountNonLocked: ").append(this.accountNonLocked)
.append("; ");
if (!authorities.isEmpty()) {
sb.append("Granted Authorities: ");
boolean first = true;
for (GrantedAuthority auth : authorities) {
if (!first) {
sb.append(",");
}
first = false;
sb.append(auth);
}
} else {
sb.append("Not granted any authorities");
}
return sb.toString();
}
}
在程序中获取用户信息:
MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
int userId=userDetails.getUserId();
在页面中获取用户信息:
<sec:authentication property="principal.realname"></sec:authentication>