所需jar包:
主要Java代码:
Java Bean:
SysAuthorities.java
package com.gwtjs.spring.security.entity;
import java.util.HashSet;
import java.util.Set;
/**
*/
public class SysAuthorities implements java.io.Serializable {
private static final long serialVersionUID = -4801194007116415993L;
private String authorityId;
private String authorityName;
private String authorityDesc;
private Boolean enabled;
private Boolean issys;
private String module;
private Set sysRolesAuthoritieses = new HashSet(0);
private Set sysAuthoritiesResources = new HashSet(0);
public SysAuthorities() {
}
public SysAuthorities(String authorityId) {
this.authorityId = authorityId;
}
public SysAuthorities(String authorityId, String authorityName,
String authorityDesc, Boolean enabled, Boolean issys, String module,
Set sysRolesAuthoritieses, Set sysAuthoritiesResources) {
this.authorityId = authorityId;
this.authorityName = authorityName;
this.authorityDesc = authorityDesc;
this.enabled = enabled;
this.issys = issys;
this.module = module;
this.sysRolesAuthoritieses = sysRolesAuthoritieses;
this.sysAuthoritiesResources = sysAuthoritiesResources;
}
public String getAuthorityId() {
return this.authorityId;
}
public void setAuthorityId(String authorityId) {
this.authorityId = authorityId;
}
public String getAuthorityName() {
return this.authorityName;
}
public void setAuthorityName(String authorityName) {
this.authorityName = authorityName;
}
public String getAuthorityDesc() {
return this.authorityDesc;
}
public void setAuthorityDesc(String authorityDesc) {
this.authorityDesc = authorityDesc;
}
public Boolean getEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getIssys() {
return this.issys;
}
public void setIssys(Boolean issys) {
this.issys = issys;
}
public String getModule() {
return this.module;
}
public void setModule(String module) {
this.module = module;
}
public Set getSysRolesAuthoritieses() {
return this.sysRolesAuthoritieses;
}
public void setSysRolesAuthoritieses(Set sysRolesAuthoritieses) {
this.sysRolesAuthoritieses = sysRolesAuthoritieses;
}
public Set getSysAuthoritiesResources() {
return this.sysAuthoritiesResources;
}
public void setSysAuthoritiesResources(Set sysAuthoritiesResources) {
this.sysAuthoritiesResources = sysAuthoritiesResources;
}
}
package com.gwtjs.spring.security.entity;
public class SysAuthoritiesResources implements java.io.Serializable {
private static final long serialVersionUID = 1898413584065943389L;
private long id;
private SysAuthorities sysAuthorities;
private SysResources sysResources;
private Boolean enabled;
public SysAuthoritiesResources() {
}
public SysAuthoritiesResources(long id) {
this.id = id;
}
public SysAuthoritiesResources(long id, SysAuthorities sysAuthorities,
SysResources sysResources, Boolean enabled) {
this.id = id;
this.sysAuthorities = sysAuthorities;
this.sysResources = sysResources;
this.enabled = enabled;
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public SysAuthorities getSysAuthorities() {
return this.sysAuthorities;
}
public void setSysAuthorities(SysAuthorities sysAuthorities) {
this.sysAuthorities = sysAuthorities;
}
public SysResources getSysResources() {
return this.sysResources;
}
public void setSysResources(SysResources sysResources) {
this.sysResources = sysResources;
}
public Boolean getEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
}
package com.gwtjs.spring.security.entity;
import java.util.HashSet;
import java.util.Set;
/**
*/
public class SysResources implements java.io.Serializable {
/**
*/
private static final long serialVersionUID = 7846668305216709567L;
private String resourceId;
private String resourceName;
private String resourceDesc;
private String resourceType;
private String resourceString;
private Boolean priority;
//是否可用,0为不可用,1为可用。
private Integer enabled;
//是否是超级。0为不超级,1为超级。
private Integer issys;
private String module;
private Set sysAuthoritiesResourceses = new HashSet(0);
public SysResources() {
}
public SysResources(String resourceId) {
this.resourceId = resourceId;
}
public SysResources(String resourceId, String resourceName,
String resourceDesc, String resourceType, String resourceString,
Boolean priority, Integer enabled, Integer issys, String module,
Set sysAuthoritiesResourceses) {
this.resourceId = resourceId;
this.resourceName = resourceName;
this.resourceDesc = resourceDesc;
this.resourceType = resourceType;
this.resourceString = resourceString;
this.priority = priority;
this.enabled = enabled;
this.issys = issys;
this.module = module;
this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;
}
public String getResourceId() {
return this.resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getResourceName() {
return this.resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getResourceDesc() {
return this.resourceDesc;
}
public void setResourceDesc(String resourceDesc) {
this.resourceDesc = resourceDesc;
}
public String getResourceType() {
return this.resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public String getResourceString() {
return this.resourceString;
}
public void setResourceString(String resourceString) {
this.resourceString = resourceString;
}
public Boolean getPriority() {
return this.priority;
}
public void setPriority(Boolean priority) {
this.priority = priority;
}
public Integer getEnabled() {
return this.enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
public Integer getIssys() {
return this.issys;
}
public void setIssys(Integer issys) {
this.issys = issys;
}
public String getModule() {
return this.module;
}
public void setModule(String module) {
this.module = module;
}
public Set getSysAuthoritiesResourceses() {
return this.sysAuthoritiesResourceses;
}
public void setSysAuthoritiesResourceses(Set sysAuthoritiesResourceses) {
this.sysAuthoritiesResourceses = sysAuthoritiesResourceses;
}
}
package com.gwtjs.spring.security.entity;
import java.util.HashSet;
import java.util.Set;
/**
*/
public class SysRoles implements java.io.Serializable {
private static final long serialVersionUID = 8069033086159154327L;
private String roleId;
private String roleName;
private String roleDesc;
private Boolean enabled;
private Boolean issys;
//平台中的子系统
private String module;
//系统用户,这层可以省
private Set sysUsersRoles = new HashSet(0);
//系统权限
private Set sysRolesAuthorities = new HashSet(0);
public SysRoles() {
}
public SysRoles(String roleId) {
this.roleId = roleId;
}
public SysRoles(String roleId, String roleName, String roleDesc) {
this.roleId = roleId;
this.roleName = roleName;
this.roleDesc = roleDesc;
}
public SysRoles(String roleId, String roleName, String roleDesc,
Boolean enabled, Boolean issys, String module) {
this.roleId = roleId;
this.roleName = roleName;
this.roleDesc = roleDesc;
this.enabled = enabled;
this.issys = issys;
this.module = module;
}
public SysRoles(String roleId, String roleName, String roleDesc,
Boolean enabled, Boolean issys, String module, Set sysUsersRoles,
Set sysRolesAuthorities) {
this.roleId = roleId;
this.roleName = roleName;
this.roleDesc = roleDesc;
this.enabled = enabled;
this.issys = issys;
this.module = module;
this.sysUsersRoles = sysUsersRoles;
this.sysRolesAuthorities = sysRolesAuthorities;
}
public String getRoleId() {
return this.roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
public Boolean getEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getIssys() {
return this.issys;
}
public void setIssys(Boolean issys) {
this.issys = issys;
}
public String getModule() {
return this.module;
}
public void setModule(String module) {
this.module = module;
}
public Set getSysUsersRoles() {
return this.sysUsersRoles;
}
public void setSysUsersRoles(Set sysUsersRoles) {
this.sysUsersRoles = sysUsersRoles;
}
public Set getSysRolesAuthorities() {
return this.sysRolesAuthorities;
}
public void setSysRolesAuthorities(Set sysRolesAuthorities) {
this.sysRolesAuthorities = sysRolesAuthorities;
}
/*
* 若要把持久类的实例放入Set中(尤其表示多值关联时),或重用脱管实例,
* 就要重写该持久类的equals和hashCode。
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals( Object other ){
if( this == other ) return true;
if( !( other instanceof SysRoles ) ) return false;
final SysRoles sysRoles = (SysRoles)other;
if( !sysRoles.getRoleName().equals( getRoleName() ) ) return false;
if( !sysRoles.getRoleDesc().equals( getRoleDesc())) return false;
return true;
}
/*
* 重写hashCode()。
* @see java.lang.Object#hashCode()
*/
public int hashCode(){
int result;
result = getRoleName().hashCode();
result = 29 * result + getRoleDesc().hashCode();
return result;
}
public static void main(String[] args){
SysRoles role1 = new SysRoles("1","lxb","ljh");
SysRoles role2 = new SysRoles("1","lxb","ljh");
/*
* 经过试验,当不重写equals和hashCode时显示为false;
* 重写时,显示为true。
* 这就是为什么重写equals和hashCode的原因,当你希望从hiberate中提取的对象实例中,
* 若是所有的字段的内容都相同时,就认为这两个对象实例是相同的,此时就需要重写equals和hashCode。
* 重写equals和hashCode意味着,混杂在不同上下文及Session中的两个实例对象有了确定的语义。
*/
System.out.println(role1.equals(role2));
/*
* 经过试验,当不重写equals和hashCode时显示为false;
* 重写时,显示为true。
*
*/
System.out.println(role1.hashCode() == role2.hashCode());
}
}
package com.gwtjs.spring.security.entity;
public class SysRolesAuthorities implements java.io.Serializable {
private static final long serialVersionUID = -1525218519228173258L;
private long id;
private SysAuthorities sysAuthorities;
private SysRoles sysRoles;
// private String roleId;
// private String authorityId;
private Boolean enabled;
public SysRolesAuthorities() {
}
public SysRolesAuthorities(long id) {
this.id = id;
}
public SysRolesAuthorities(long id, SysAuthorities sysAuthorities,
SysRoles sysRoles, Boolean enabled) {
this.id = id;
this.sysAuthorities = sysAuthorities;
this.sysRoles = sysRoles;
this.enabled = enabled;
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public SysAuthorities getSysAuthorities() {
return this.sysAuthorities;
}
public void setSysAuthorities(SysAuthorities sysAuthorities) {
this.sysAuthorities = sysAuthorities;
}
public SysRoles getSysRoles() {
return this.sysRoles;
}
public void setSysRoles(SysRoles sysRoles) {
this.sysRoles = sysRoles;
}
public Boolean getEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
// public String getRoleId(){
// return roleId;
// }
//
// public void setRoleId( String roleId ){
// this.roleId = roleId;
// }
//
// public String getAuthorityId(){
// return authorityId;
// }
//
// public void setAuthorityId( String authorityId ){
// this.authorityId = authorityId;
// }
}
package com.gwtjs.spring.security.entity;
import java.io.Serializable;
public class SysUnit implements Serializable {
private static final long serialVersionUID = -7923159128209952650L;
private Long id;
private String unitName;
private String unitDesc;
private Integer enabled;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
public String getUnitDesc() {
return unitDesc;
}
public void setUnitDesc(String unitDesc) {
this.unitDesc = unitDesc;
}
public Integer getEnabled() {
return enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
}
package com.gwtjs.spring.security.entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;
import com.gwtjs.spring.security.CustomUserDetails;
/**
*/
public class SysUsers implements CustomUserDetails,java.io.Serializable {
/**
*/
private static final long serialVersionUID = 1259675211426094628L;
//用户id
private String userId;
//用户账号 与 用户id相同,具有唯一性。
private String userAccount;
//中文用户名。
private String userName;
//密码原文 + 用户名作为盐值 的字串经过Md5加密后形成的密文。
private String userPassword;
//用户备注
private String userDesc;
//是否能用。
private Boolean enabled;
//是否是超级用户。
private Boolean issys;
//用户所在的单位。
private String userDept;
//用户的职位:比如主任、经理等。
private String userDuty;
//该用户所负责的子系统
private String subSystem;
//一个用户具有多个角色。
private Set sysUsersRoleses = new HashSet(0);
//实现了UserDetails之后的相关变量
private String password;
private String username;
private Set authorities;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
public SysUsers(){
}
public SysUsers(String userId, String userAccount, String userName,
String userPassword, String userDesc, Boolean enabled,
Boolean issys, String userDuty, String userDept, String subSystem, Set sysUsersRoleses,boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Collection authorities) {
if (((userAccount == null) || "".equals(userAccount)) || (userPassword == null)) {
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.userId = userId;
this.userAccount = userAccount;
this.userName = userName;
this.userPassword = userPassword;
this.userDesc = userDesc;
this.issys = issys;
this.userDuty = userDuty;
this.userDept = userDept;
this.subSystem = subSystem;
this.sysUsersRoleses = sysUsersRoleses;
this.username = userAccount;
this.password = userPassword;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserAccount() {
return this.userAccount;
}
public void setUserAccount(String userAccount) {
this.userAccount = userAccount;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return this.userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserDesc() {
return this.userDesc;
}
public void setUserDesc(String userDesc) {
this.userDesc = userDesc;
}
public boolean getEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Boolean getIssys() {
return this.issys;
}
public void setIssys(Boolean issys) {
this.issys = issys;
}
public String getUserDept() {
return this.userDept;
}
public void setUserDept(String userDept) {
this.userDept = userDept;
}
public String getUserDuty() {
return this.userDuty;
}
public void setUserDuty(String userDuty) {
this.userDuty = userDuty;
}
public String getSubSystem() {
return this.subSystem;
}
public void setSubSystem(String subSystem) {
this.subSystem = subSystem;
}
public Set getSysUsersRoleses() {
return this.sysUsersRoleses;
}
public void setSysUsersRoleses(Set sysUsersRoleses) {
this.sysUsersRoleses = sysUsersRoleses;
}
//~ Methods ========================================================================================================
public boolean equals(Object rhs) {
if (!(rhs instanceof SysUsers) || (rhs == null)) {
return false;
}
SysUsers user = (SysUsers) rhs;
//具有的权限。
if (!authorities.equals(user.authorities)) {
return false;
}
// 通过Spring Security构建一个用户时,用户名和密码不能为空。
return (this.getPassword().equals(user.getPassword()) && this.getUsername().equals(user.getUsername())
&& (this.isAccountNonExpired() == user.isAccountNonExpired())
&& (this.isAccountNonLocked() == user.isAccountNonLocked())
&& (this.isCredentialsNonExpired() == user.isCredentialsNonExpired())
&& (this.isEnabled() == user.isEnabled()));
}
public Collection getAuthorities() {
return authorities;
}
public void setAuthorities( Collection authorities ){
this.authorities = (Set) authorities;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public int hashCode() {
int code = 9792;
//若该用户不是登录人员,则可以允许没有authorities。
if (null != getUsername() && null != getAuthorities()) {
for (GrantedAuthority authority : getAuthorities()) {
code = code * (authority.hashCode() % 7);
}
}
if (this.getPassword() != null) {
code = code * (this.getPassword().hashCode() % 7);
}
if (this.getUsername() != null) {
code = code * (this.getUsername().hashCode() % 7);
}
if (this.isAccountNonExpired()) {
code = code * -2;
}
if (this.isAccountNonLocked()) {
code = code * -3;
}
if (this.isCredentialsNonExpired()) {
code = code * -5;
}
if (this.isEnabled()) {
code = code * -7;
}
return code;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return this.accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public boolean isEnabled() {
return enabled;
}
private static SortedSet sortAuthorities(Collection 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 sortedAuthorities =
new TreeSet(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, Serializable {
private static final long serialVersionUID = 6173956575005152011L;
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());
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("Username: ").append(this.username).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("UserAccount: ").append(this.userAccount).append("; ");
sb.append("UserDept: ").append(this.userDept).append("; ");
sb.append("UserDuty: ").append(this.userDuty).append("; ");
sb.append("UserDesc: ").append(this.userDesc).append("; ");
sb.append("UserSubSystem: ").append(this.subSystem).append("; ");
sb.append("UserIsSys: ").append(this.issys).append("; ");
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 ( null !=authorities && !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();
}
public static void main(String[] args){
}
}
package com.gwtjs.spring.security.entity;
public class SysUsersRoles implements java.io.Serializable {
private static final long serialVersionUID = 7198583470977284717L;
private long id;
private SysUsers sysUsers;
private SysRoles sysRoles;
private Boolean enabled;
public SysUsersRoles() {
}
public SysUsersRoles(long id) {
this.id = id;
}
public SysUsersRoles(long id, SysUsers sysUsers, SysRoles sysRoles,
Boolean enabled) {
this.id = id;
this.sysUsers = sysUsers;
this.sysRoles = sysRoles;
this.enabled = enabled;
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public SysUsers getSysUsers() {
return this.sysUsers;
}
public void setSysUsers(SysUsers sysUsers) {
this.sysUsers = sysUsers;
}
public SysRoles getSysRoles() {
return this.sysRoles;
}
public void setSysRoles(SysRoles sysRoles) {
this.sysRoles = sysRoles;
}
public Boolean getEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
}
Dao Interface
package com.gwtjs.spring.security.dao.impl;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.gwtjs.dao.impl.GenericDaoImpl;
import com.gwtjs.spring.security.dao.SysAuthoritiesDao;
import com.gwtjs.spring.security.dao.SysAuthoritiesResourcesDao;
import com.gwtjs.spring.security.dao.SysResourcesDao;
import com.gwtjs.spring.security.entity.SysAuthorities;
import com.gwtjs.spring.security.entity.SysAuthoritiesResources;
import com.gwtjs.spring.security.entity.SysResources;
import com.gwtjs.utils.Util;
/**
* Home object for domain model class SysAuthorities.
* @see com.gwtjs.spring.security.entity.SysAuthorities
*/
@Repository(value="sysAuthoritiesDao")
public class SysAuthoritiesDaoImpl extends GenericDaoImpl implements SysAuthoritiesDao {
private static final Log log = LogFactory.getLog(SysAuthoritiesDaoImpl.class);
//资源dao
@Autowired private SysResourcesDao sysResourcesDao;
//权限和资源对应关系的dao
@Autowired private SysAuthoritiesResourcesDao sysAuthoritiesResourcesDao;
/*
* 将从页面返回的权限对象进行保存。
*/
public void persist(SysAuthorities transientInstance) {
log.debug("权限 " + transientInstance.getAuthorityDesc() + " 持久化!");
try {
// 为写入的权限设置唯一id
transientInstance.setAuthorityId(Util.getPkId() + "");
String authorityName = transientInstance.getAuthorityName();
// 当权限标识前缀不为"AUTH_"时,要添加该标识。
if (authorityName.startsWith("AUTH")) {
if (!authorityName.startsWith("AUTH_")) {
authorityName = authorityName.substring(0, 4) + "_"
+ authorityName.substring(4);
transientInstance.setAuthorityName(authorityName);
}
} else {
transientInstance.setAuthorityName("AUTH_" + authorityName);
}
// 持久化
getSession().persist(transientInstance);
log.debug("权限 " + transientInstance.getAuthorityDesc() + " 持久化成功!");
} catch (RuntimeException re) {
log.error("权限 " + transientInstance.getAuthorityDesc() + " 持久化失败!", re);
throw re;
}
}
/*
* 对权限实例进行更新。
*/
public void attachDirty(SysAuthorities instance) {
log.debug("更新权限" + instance.getAuthorityName() + "!");
try {
getSession().saveOrUpdate(instance);
log.debug("更新权限 " + instance.getAuthorityName() + "成功!");
} catch (RuntimeException re) {
log.error("更新权限 " + instance.getAuthorityName() + "失败!", re);
throw re;
}
}
public void attachClean(SysAuthorities instance) {
log.debug("attaching clean SysAuthorities instance");
try {
lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
/**
* 根据权限id删除该权限,角色和权限,权限和资源的关系。
*
* @author aGuang 2011-4-10 下午03:31:22
*@param authorityId
*/
public void delete(String authorityId) {
log.debug("根据权限id删除该权限!权限id为 : " + authorityId);
try {
SysAuthorities authority = findById( authorityId );
getSession().delete( authority );
log.debug("权限id" + authorityId + "删除成功!");
} catch (RuntimeException re) {
log.error("权限id" + authorityId + "删除失败!", re);
throw re;
}
}
/**
* 通过id得以权限的实例。
*@author aGuang 2011-4-20 上午09:17:02
*@param id
*@return
*/
public SysAuthorities findById( String id ) {
log.debug("通过id得到权限类的实例: " + id);
try {
SysAuthorities instance = (SysAuthorities) getSession().createQuery( "from SysAuthorities where authority_id='" + id + "'").uniqueResult();
if (instance == null) {
log.debug("该权限类不存在!");
} else {
log.debug("成功找到该权限类的实例!");
}
return instance;
} catch (RuntimeException re) {
log.error("查找权限类实例失败!", re);
throw re;
}
}
/**
* 根据平台中的子系统返回权限列表。
*
* @author aGuang 2011-4-23 下午18:32:38
*@return
*/
@SuppressWarnings("unchecked")
public List findAuthoritiesLst(String xtmk) {
try {
List results = getSession().createQuery("from SysAuthorities where module='" + xtmk + "'").list();
return results;
} catch (RuntimeException re) {
throw re;
}
}
/**
* 根据权限id,得到以资源id为键,"true"为值的Map。
*
* @author aGuang 2011-4-23 下午18:15:21
*@param authorityId
*@return
*/
@SuppressWarnings("unchecked")
public HashMap getSelectedResourcesMap(String authorityId) {
try {
List results = getSession().createSQLQuery("select a.resource_id " +
"from Sys_Resources a, Sys_Authorities_Resources b " +
"where a.resource_id = b.resource_id and b.Authority_id='"+
authorityId +"' and a.enabled=1").list();
HashMap hashMap = new HashMap(0);
for (String resourcesId : results) {
hashMap.put( resourcesId, "true" );
}
return hashMap;
} catch (RuntimeException re) {
throw re;
}
}
/*
* 保存权限和资源之间一对多的关系。
*/
public boolean saveAuthorityAndReSource(String authorityId, String[] resourceskey) {
SysAuthorities sysAuthorities = findById(authorityId);
SysResources sysResources = null;
SysAuthoritiesResources sysAuthoritiesResources;
//在重新设置之前先删除之前所拥有的全部对应关系
sysAuthoritiesResourcesDao.deleteOldAuthorityAndResourceRelative( authorityId );
try {
/*
* 将用户在前台通过checkbox选中的所有权限id提取出来。
* 在进行保存之前,首先要通过id提取该权限的实例,
* 为角色权限关联表sysRolesAuthorities的setSysAuthorities()提供数据。
* 最后通过hibernate的save()方法保存新建的sysRolesAuthorities实例。
*/
for (String resId : resourceskey) {
sysResources = sysResourcesDao.findById( resId );
/*
* 生成一个新的实例很重要,否则会报
* identifier of an instance of xxx
* was altered from xxx to xxx"的异常。
*/
sysAuthoritiesResources = new SysAuthoritiesResources();
sysAuthoritiesResources.setId( Util.getPkId() );
sysAuthoritiesResources.setSysResources( sysResources );
sysAuthoritiesResources.setSysAuthorities( sysAuthorities );
sysAuthoritiesResources.setEnabled(true);
getSession().save( sysAuthoritiesResources );
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* 得到资源列表。
*/
@SuppressWarnings("unchecked")
public List getResourcesList() {
try {
return getSession().createQuery("from SysResources where enabled=1").list();
} catch (RuntimeException re) {
throw re;
}
}
/**
* 提取系统中的所有权限
* @return
*/
@SuppressWarnings("unchecked")
public List getSysAuthorities(){
String sql = "select authority_name from sys_authorities";
List query = getSession().createSQLQuery(sql).list();
return query;
}
/*//注入
public void setSysResourcesDao( SysResourcesDao sysResourcesDao){
this.sysResourcesDao = sysResourcesDao;
}
public SysResourcesDao getSysResourcesDao(){
return sysResourcesDao;
}
public void setSysRolesAuthoritiesDao( SysRolesAuthoritiesDao sysRolesAuthoritiesDao){
this.sysRolesAuthoritiesDao = sysRolesAuthoritiesDao;
}
public SysRolesAuthoritiesDao getSysRolesAuthoritiesDao(){
return sysRolesAuthoritiesDao;
}
public SysAuthoritiesResourcesDao getSysAuthoritiesResourcesDao(){
return sysAuthoritiesResourcesDao;
}
public void setSysAuthoritiesResourcesDao( SysAuthoritiesResourcesDao sysAuthoritiesResourcesDao){
this.sysAuthoritiesResourcesDao = sysAuthoritiesResourcesDao;
}*/
}
package com.gwtjs.spring.security.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.Example;
import org.springframework.stereotype.Repository;
import com.gwtjs.dao.impl.GenericDaoImpl;
import com.gwtjs.spring.security.dao.SysAuthoritiesResourcesDao;
import com.gwtjs.spring.security.entity.SysAuthoritiesResources;
/**
* Home object for domain model class SysAuthoritiesResources.
* @see com.gwtjs.spring.security.entity.SysAuthoritiesResources
* @author Hibernate Tools
*/
@Repository(value="sysAuthoritiesResourcesDao")
public class SysAuthoritiesResourcesDaoImpl extends GenericDaoImpl implements SysAuthoritiesResourcesDao{
private static final Log log = LogFactory
.getLog(SysAuthoritiesResourcesDaoImpl.class);
@SuppressWarnings("unchecked")
public List loadResource(String auth){
return getSession()
.createSQLQuery(
"select b.resource_string "
+ "from Sys_Authorities_Resources a, Sys_Resources b, "
+ "Sys_authorities c where a.resource_id = b.resource_id "
+ "and a.authority_id=c.authority_id and c.Authority_name='"
+ auth + "'").list();
}
public void persist(SysAuthoritiesResources transientInstance) {
log.debug("persisting SysAuthoritiesResources instance");
try {
getSession().persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void attachDirty(SysAuthoritiesResources instance) {
log.debug("attaching dirty SysAuthoritiesResources instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(SysAuthoritiesResources instance) {
log.debug("attaching clean SysAuthoritiesResources instance");
try {
lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void delete(SysAuthoritiesResources persistentInstance) {
log.debug("deleting SysAuthoritiesResources instance");
try {
getSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public SysAuthoritiesResources merge(
SysAuthoritiesResources detachedInstance) {
log.debug("merging SysAuthoritiesResources instance");
try {
SysAuthoritiesResources result = (SysAuthoritiesResources) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public SysAuthoritiesResources findById(long id) {
log.debug("getting SysAuthoritiesResources instance with id: " + id);
try {
SysAuthoritiesResources instance = (SysAuthoritiesResources) getSession()
.get("com.gwtjs.spring.security.entity.SysAuthoritiesResources", id);
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
/**
* 得到PubAuthoritiesResources的对象列表。
*@author aGuang 2011-3-23 下午02:33:05
*@return
*/
@SuppressWarnings("unchecked")
public List getAll(){
List auths = new ArrayList();
try{
auths = getSession().createQuery("from SysAuthoritiesResources").list();
return auths;
}catch( RuntimeException re ){
log.error("find by authorities failed.", re);
throw re;
}
}
/**
* 根据权限id删除权限与资源之间旧有的关联关系。
*@author aGuang 2011-4-23 上午10:14:29
*@param authorityId
*/
public void deleteOldAuthorityAndResourceRelative( String authorityId ){
try{
getSession().createSQLQuery("delete Sys_Authorities_Resources where authority_id='" + authorityId + "'");
log.info("删除权限与资源之间的关联关系成功!");
}catch(RuntimeException re){
log.error("删除权限与资源之间的关联关系失败!");
throw re;
}
}
@SuppressWarnings("unchecked")
public List findByExample(SysAuthoritiesResources instance) {
log.debug("finding SysAuthoritiesResources instance by example");
try {
List results = getSession().createCriteria(
"com.gwtjs.spring.security.entity.SysAuthoritiesResources").add(
Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
}
核心的服务类Services
/*
* @(#) MyAccessDecisionManager.java 2011-3-23 下午04:41:12
*
* Copyright 2011 by aGuang
*/
package com.gwtjs.spring.security;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
/**
*AccessdecisionManager在Spring security中是很重要的。
*
*在验证部分简略提过了,所有的Authentication实现需要保存在一个GrantedAuthority对象数组中。
*这就是赋予给主体的权限。 GrantedAuthority对象通过AuthenticationManager
*保存到 Authentication对象里,然后从AccessDecisionManager读出来,进行授权判断。
*
*Spring Security提供了一些拦截器,来控制对安全对象的访问权限,例如方法调用或web请求。
*一个是否允许执行调用的预调用决定,是由AccessDecisionManager实现的。
*这个 AccessDecisionManager 被AbstractSecurityInterceptor调用,
*它用来作最终访问控制的决定。 这个AccessDecisionManager接口包含三个方法:
*
void decide(Authentication authentication, Object secureObject,
List config) throws AccessDeniedException;
boolean supports(ConfigAttribute attribute);
boolean supports(Class clazz);
从第一个方法可以看出来,AccessDecisionManager使用方法参数传递所有信息,这好像在认证评估时进行决定。
特别是,在真实的安全方法期望调用的时候,传递安全Object启用那些参数。
比如,让我们假设安全对象是一个MethodInvocation。
很容易为任何Customer参数查询MethodInvocation,
然后在AccessDecisionManager里实现一些有序的安全逻辑,来确认主体是否允许在那个客户上操作。
如果访问被拒绝,实现将抛出一个AccessDeniedException异常。
这个 supports(ConfigAttribute) 方法在启动的时候被
AbstractSecurityInterceptor调用,来决定AccessDecisionManager
是否可以执行传递ConfigAttribute。
supports(Class)方法被安全拦截器实现调用,
包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型。
*/
public class CustomAccessDecisionManager implements AccessDecisionManager {
public void decide( Authentication authentication, Object object,
Collection configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException{
if( configAttributes == null ) {
return ;
}
Iterator ite = configAttributes.iterator();
while( ite.hasNext()){
ConfigAttribute ca = ite.next();
String needRole = ((SecurityConfig)ca).getAttribute();
//ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
for( GrantedAuthority ga: authentication.getAuthorities()){
if(needRole.trim().equals(ga.getAuthority().trim())){
return;
}
}
}
throw new AccessDeniedException("");
}
public boolean supports( ConfigAttribute attribute ){
return true;
}
public boolean supports(Class> clazz){
return true;
}
}
/*
* @(#) MyFilterSecurityInterceptor.java 2011-3-23 上午07:53:03
*
* Copyright 2011 by aGuang
*/
package com.gwtjs.spring.security;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
/**
* 该过滤器的主要作用就是通过spring著名的IoC生成securityMetadataSource。
* securityMetadataSource相当于本包中自定义的MyInvocationSecurityMetadataSourceService。
* 该MyInvocationSecurityMetadataSourceService的作用提从数据库提取权限和资源,装配到HashMap中,
* 供Spring Security使用,用于权限校验。
* @author aGuang 11/3/29
*
*/
public class CustomFilterSecurityInterceptor
extends AbstractSecurityInterceptor
implements Filter{
private FilterInvocationSecurityMetadataSource securityMetadataSource;
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException{
FilterInvocation fi = new FilterInvocation( request, response, chain );
invoke(fi);
}
public FilterInvocationSecurityMetadataSource getSecurityMetadataSource(){
return this.securityMetadataSource;
}
public Class extends Object> getSecureObjectClass(){
return FilterInvocation.class;
}
public void invoke( FilterInvocation fi ) throws IOException, ServletException{
InterceptorStatusToken token = super.beforeInvocation(fi);
try{
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
}finally{
super.afterInvocation(token, null);
}
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource(){
return this.securityMetadataSource;
}
public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource){
this.securityMetadataSource = securityMetadataSource;
}
public void destroy(){
}
public void init( FilterConfig filterconfig ) throws ServletException{
}
}
/*
* @(#) MyInvocationSecurityMetadataSourceService.java 2011-3-23 下午02:58:29
*
* Copyright 2011 by aGuang
*/
package com.gwtjs.spring.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;
import com.gwtjs.spring.security.dao.SysAuthoritiesDao;
import com.gwtjs.spring.security.dao.SysAuthoritiesResourcesDao;
/**
* 最核心的地方,就是提供某个资源对应的权限定义,即getAttributes方法返回的结果。 此类在初始化时,应该取到所有资源及其对应角色的定义。
*/
//@Service
public class CustomInvocationSecurityMetadataSourceService implements
FilterInvocationSecurityMetadataSource {
@Autowired
private SysAuthoritiesDao sysAuthoritiesDao;
@Autowired()
private SysAuthoritiesResourcesDao sysAuthoritiesResourcesDao;
private UrlMatcher urlMatcher = new AntUrlPathMatcher();
private static Map> resourceMap = null;
public CustomInvocationSecurityMetadataSourceService() {
loadResourceDefine();
}
private void loadResourceDefine() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml","applicationContext-service.xml");
/*SessionFactory sessionFactory = (SessionFactory) context
.getBean("sessionFactory");
Session session = sessionFactory.openSession();*/
sysAuthoritiesDao = (SysAuthoritiesDao) context.getBean("sysAuthoritiesDao");
sysAuthoritiesResourcesDao = (SysAuthoritiesResourcesDao) context.getBean("sysAuthoritiesResourcesDao");
System.out.println("-----------------get all system authorites--------------"+sysAuthoritiesDao);
System.out.println("--------------get all system authorites resources-------------"+sysAuthoritiesResourcesDao);
// 在Web服务器启动时,提取系统中的所有权限。
// String sql = "select authority_name from sys_authorities";
List as = sysAuthoritiesDao.getSysAuthorities();
/*
* 应当是资源为key, 权限为value。 资源通常为url, 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。
* aGuang
*/
resourceMap = new HashMap>();
for (String auth : as) {
ConfigAttribute ca = new SecurityConfig(auth);
List rs = sysAuthoritiesResourcesDao.loadResource(auth);
for (String url : rs) {
/*
* 判断资源文件和权限的对应关系,如果已经存在相关的资源url,则要通过该url为key提取出权限集合,将权限增加到权限集合中。
* aGuang
*/
if (resourceMap.containsKey(url)) {
Collection value = resourceMap.get(url);
value.add(ca);
resourceMap.put(url, value);
} else {
Collection atts = new ArrayList();
atts.add(ca);
resourceMap.put(url, atts);
}
}
}
}
@Override
public Collection getAllConfigAttributes() {
return null;
}
// 根据URL,找到相关的权限配置。
@Override
public Collection getAttributes(Object object)
throws IllegalArgumentException {
// object 是一个URL,被用户请求的url。
String url = ((FilterInvocation) object).getRequestUrl();
int firstQuestionMarkIndex = url.indexOf("?");
if (firstQuestionMarkIndex != -1) {
url = url.substring(0, firstQuestionMarkIndex);
}
Iterator ite = resourceMap.keySet().iterator();
while (ite.hasNext()) {
String resURL = ite.next();
if (urlMatcher.pathMatchesUrl(url, resURL)) {
return resourceMap.get(resURL);
}
}
return null;
}
@Override
public boolean supports(Class> arg0) {
return true;
}
}
/*
* @(#) CustomUserDetails.java 2011-4-13 下午01:44:14
*
* Copyright 2011 by aGuang
*/
package com.gwtjs.spring.security;
import java.util.Set;
import org.springframework.security.core.userdetails.UserDetails;
import com.gwtjs.spring.security.entity.SysUsersRoles;
/**
*实现了UserDetails,扩展几项信息,比如getSubSystem()方法等 aGuang 2012-09-25。
*/
public interface CustomUserDetails extends UserDetails {
//用户id
public String getUserId();
//用户账户
public String getUserAccount();
//用户名
public String getUserName();
//用户密码
public String getUserPassword();
//用户描述或简介
public String getUserDesc();
//用户是否能用
public boolean getEnabled();
//是否超级用户
public Boolean getIssys();
//所属的单位
public String getUserDept();
//用户职位
public String getUserDuty();
//用户分管的子系统
public String getSubSystem();
//用户相对应的角色集
public Set getSysUsersRoleses();
}
/*
* @(#) MyUserDetailsService.java 2011-3-23 上午09:04:31
*
* Copyright 2011 by aGuang
*/
package com.gwtjs.spring.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.gwtjs.spring.security.dao.SysUsersDao;
import com.gwtjs.spring.security.dao.impl.SysUsersDaoImpl;
import com.gwtjs.spring.security.entity.SysUsers;
import com.gwtjs.spring.security.entity.SysUsersRoles;
/**
* 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails。
* 该UserDetails包括用户名、密码、是否可用、是否过期等信息。 aGuang 11/3/29
*/
//@Service(value="userDetailsManager")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private SysUsersDao sysUsersDao;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
Collection auths = new ArrayList();
if (null == sysUsersDao) {
sysUsersDao = new SysUsersDaoImpl();
}
// 得到用户的权限
auths = sysUsersDao.loadUserAuthoritiesByName(username);
// 根据用户名取得一个SysUsers对象,以获取该用户的其他信息。
SysUsers user = sysUsersDao.findByUserAccount(username);
return new SysUsers(user.getUserId(), user.getUserAccount(),
user.getUserName(), user.getUserPassword(), user.getUserDesc(),
true, false, user.getUserDuty(), user.getUserDept(),
user.getSubSystem(), new HashSet(0), true, true,
true, auths);
}
public void setSysUsersDao(SysUsersDao sysUsersDao) {
this.sysUsersDao = sysUsersDao;
}
}
主要配置:
applicationContext-service.xml
applicationContext-security.xml
下一篇: