权限开发 spring security 3.0.7 序列2

来源:互联网 发布:ipadmini下载软件 编辑:程序博客网 时间:2024/06/16 14:43

所需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<SysRolesAuthorities> sysRolesAuthoritieses = new HashSet<SysRolesAuthorities>(0);private Set<SysAuthoritiesResources> sysAuthoritiesResources = new HashSet<SysAuthoritiesResources>(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<SysRolesAuthorities> sysRolesAuthoritieses, Set<SysAuthoritiesResources> 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<SysRolesAuthorities> getSysRolesAuthoritieses() {return this.sysRolesAuthoritieses;}public void setSysRolesAuthoritieses(Set<SysRolesAuthorities> sysRolesAuthoritieses) {this.sysRolesAuthoritieses = sysRolesAuthoritieses;}public Set<SysAuthoritiesResources> getSysAuthoritiesResources() {return this.sysAuthoritiesResources;}public void setSysAuthoritiesResources(Set<SysAuthoritiesResources> 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<SysAuthoritiesResources> sysAuthoritiesResourceses = new HashSet<SysAuthoritiesResources>(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<SysAuthoritiesResources> 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<SysAuthoritiesResources> getSysAuthoritiesResourceses() {return this.sysAuthoritiesResourceses;}public void setSysAuthoritiesResourceses(Set<SysAuthoritiesResources> 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> sysUsersRoles = new HashSet<SysUsersRoles>(0);//系统权限private Set<SysRolesAuthorities> sysRolesAuthorities = new HashSet<SysRolesAuthorities>(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> sysUsersRoles,Set<SysRolesAuthorities> 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<SysUsersRoles> getSysUsersRoles() {return this.sysUsersRoles;}public void setSysUsersRoles(Set<SysUsersRoles> sysUsersRoles) {this.sysUsersRoles = sysUsersRoles;}public Set<SysRolesAuthorities> getSysRolesAuthorities() {return this.sysRolesAuthorities;}public void setSysRolesAuthorities(Set<SysRolesAuthorities> 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;//用户idprivate 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<SysUsersRoles> sysUsersRoleses = new HashSet<SysUsersRoles>(0);//实现了UserDetails之后的相关变量    private  String password;    private  String username;    private  Set<GrantedAuthority> 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<SysUsersRoles> sysUsersRoleses,boolean accountNonExpired,            boolean credentialsNonExpired, boolean accountNonLocked, Collection<GrantedAuthority> 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<SysUsersRoles> getSysUsersRoleses() {return this.sysUsersRoleses;}public void setSysUsersRoleses(Set<SysUsersRoles> 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<GrantedAuthority> getAuthorities() {        return authorities;    }        public void setAuthorities( Collection<GrantedAuthority> authorities ){    this.authorities = (Set<GrantedAuthority>) 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<GrantedAuthority> sortAuthorities(Collection<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 {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;}}

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping >    <class name="com.gwtjs.spring.security.entity.SysAuthorities" table="SYS_AUTHORITIES" >        <id name="authorityId" type="string">            <column name="AUTHORITY_ID" length="32" />            <generator class="assigned" />        </id>        <property name="authorityName" type="string">            <column name="AUTHORITY_NAME" length="40" />        </property>        <property name="authorityDesc" type="string">            <column name="AUTHORITY_DESC" length="100" />        </property>        <property name="enabled" type="java.lang.Boolean">            <column name="ENABLED" precision="1" scale="0" />        </property>        <property name="issys" type="java.lang.Boolean">            <column name="ISSYS" precision="1" scale="0" />        </property>        <property name="module" type="string">            <column name="MODULE" length="4" />        </property>        <set name="sysRolesAuthoritieses" inverse="true" cascade="all">            <key>                <column name="AUTHORITY_ID" length="32" />            </key>            <one-to-many class="com.gwtjs.spring.security.entity.SysRolesAuthorities" />        </set>        <set name="sysAuthoritiesResources" inverse="true" cascade="all">            <key>                <column name="AUTHORITY_ID" length="32" />            </key>            <one-to-many class="com.gwtjs.spring.security.entity.SysAuthoritiesResources" />        </set>    </class></hibernate-mapping><?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping >    <class name="com.gwtjs.spring.security.entity.SysAuthoritiesResources" table="SYS_AUTHORITIES_RESOURCES" >        <id name="id" type="long">            <column name="ID" precision="13" scale="0" />            <generator class="assigned" />        </id>        <many-to-one name="sysAuthorities" class="com.gwtjs.spring.security.entity.SysAuthorities" fetch="select">            <column name="AUTHORITY_ID" length="32" />        </many-to-one>        <many-to-one name="sysResources" class="com.gwtjs.spring.security.entity.SysResources" fetch="select">            <column name="RESOURCE_ID" length="32" />        </many-to-one>        <property name="enabled" type="java.lang.Boolean">            <column name="ENABLED" precision="1" scale="0" />        </property>    </class></hibernate-mapping><?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping >    <class name="com.gwtjs.spring.security.entity.SysResources" table="Sys_RESOURCES">        <id name="resourceId" type="string">            <column name="RESOURCE_ID" length="32" />            <generator class="assigned" />        </id>        <property name="resourceName" type="string" unique="true">            <column name="RESOURCE_NAME" length="100" />        </property>        <property name="resourceDesc" type="string">            <column name="RESOURCE_DESC" length="100" />        </property>        <property name="resourceType" type="string">            <column name="RESOURCE_TYPE" length="40" />        </property>        <property name="resourceString" type="string">            <column name="RESOURCE_STRING" length="200" />        </property>        <property name="priority" type="java.lang.Boolean">            <column name="PRIORITY" precision="1" scale="0" />        </property>        <property name="enabled" type="java.lang.Integer">            <column name="ENABLED" precision="1" scale="0" />        </property>        <property name="issys" type="java.lang.Integer">            <column name="ISSYS" precision="1" scale="0" />        </property>        <property name="module" type="string">            <column name="MODULE" length="6" />        </property>        <set name="sysAuthoritiesResourceses" inverse="true" fetch="join" lazy="false">            <key>                <column name="RESOURCE_ID" length="32" />            </key>            <one-to-many class="com.gwtjs.spring.security.entity.SysAuthoritiesResources" />        </set>    </class></hibernate-mapping>

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping >    <class name="com.gwtjs.spring.security.entity.SysRoles" table="SYS_ROLES">        <id name="roleId" type="string">            <column name="ROLE_ID" length="32" />            <generator class="assigned" />        </id>        <property name="roleName" type="string" unique="true">            <column name="ROLE_NAME" length="40" />        </property>        <property name="roleDesc" type="string">            <column name="ROLE_DESC" length="100" />        </property>        <property name="enabled" type="java.lang.Boolean">            <column name="ENABLED" precision="1" scale="0" />        </property>        <property name="issys" type="java.lang.Boolean">            <column name="ISSYS" precision="1" scale="0" />        </property>        <property name="module" type="string">            <column name="MODULE" length="32" />        </property>        <set name="sysUsersRoles" inverse="true" cascade="all"  fetch="join" lazy="false">            <key>                <column name="ROLE_ID" length="32" />            </key>            <one-to-many class="com.gwtjs.spring.security.entity.SysUsersRoles" />        </set>        <set name="sysRolesAuthorities" inverse="true" cascade="all" fetch="join" lazy="false">            <key>                <column name="ROLE_ID" length="32" />            </key>            <one-to-many class="com.gwtjs.spring.security.entity.SysRolesAuthorities" />        </set>    </class></hibernate-mapping><?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping >    <class name="com.gwtjs.spring.security.entity.SysRolesAuthorities" table="SYS_ROLES_AUTHORITIES">        <id name="id" type="long">            <column name="ID" precision="13" scale="0" />            <generator class="assigned" />        </id>        <many-to-one name="sysAuthorities" class="com.gwtjs.spring.security.entity.SysAuthorities" fetch="select" lazy="false">            <column name="AUTHORITY_ID" length="32" />        </many-to-one>        <many-to-one name="sysRoles" class="com.gwtjs.spring.security.entity.SysRoles" fetch="select" lazy="false">            <column name="ROLE_ID" length="32" />        </many-to-one>        <!--          <property name="authorityId" type="string">            <column name="AUTHORITY_ID" length="32" />        </property>        <property name="roleId" type="string">            <column name="ROLE_ID" length="32" />        </property> -->        <property name="enabled" type="java.lang.Boolean">            <column name="ENABLED" precision="1" scale="0" />        </property>    </class></hibernate-mapping>

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.gwtjs.spring.security.entity.SysUnit" table="SYS_Unit"><id name="id" ><column name="UNIT_ID" length="32" /><generator class="assigned" /></id><property name="unitName" type="string" unique="true"><column name="unit_Name" length="64" /></property><property name="unitDesc" type="string" unique="true"><column name="unit_Desc" length="140" /></property><property name="enabled" type="java.lang.Boolean"><column name="ENABLED" precision="1" scale="0" /></property></class></hibernate-mapping><?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="com.gwtjs.spring.security.entity.SysUsers" table="SYS_USERS"><id name="userId" type="string"><column name="USER_ID" length="32" /><generator class="assigned" /></id><property name="userAccount" type="string" unique="true"><column name="USER_ACCOUNT" length="30" /></property><property name="userName" type="string" unique="true"><column name="USER_NAME" length="40" /></property><property name="userPassword" type="string"><column name="USER_PASSWORD" length="100" /></property><property name="userDesc" type="string"><column name="USER_DESC" length="100" /></property><property name="userDuty" type="string"><column name="USER_DUTY" length="10" /></property><property name="userDept" type="string"><column name="USER_DEPT" length="20" /></property><property name="subSystem" type="string"><column name="SUB_SYSTEM" length="30" /></property><property name="enabled" type="java.lang.Boolean"><column name="ENABLED" precision="1" scale="0" /></property><property name="issys" type="java.lang.Boolean"><column name="ISSYS" precision="1" scale="0" /></property><set name="sysUsersRoleses" inverse="true" cascade="all" lazy="false" fetch="join"><key><column name="USER_ID" length="32" /></key><one-to-many class="com.gwtjs.spring.security.entity.SysUsersRoles" /></set></class></hibernate-mapping>

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping >    <class name="com.gwtjs.spring.security.entity.SysUsersRoles" table="SYS_USERS_ROLES" >        <id name="id" type="long">            <column name="ID" precision="13" scale="0" />            <generator class="assigned" />        </id>        <many-to-one name="sysUsers" class="com.gwtjs.spring.security.entity.SysUsers" fetch="join" lazy="false" >            <column name="USER_ID" length="32" />        </many-to-one>        <many-to-one name="sysRoles" class="com.gwtjs.spring.security.entity.SysRoles" fetch="join" lazy="false" >            <column name="ROLE_ID" length="32" />        </many-to-one>        <property name="enabled" type="java.lang.Boolean">            <column name="ENABLED" precision="1" scale="0" />        </property>    </class></hibernate-mapping>



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<SysAuthorities,String> 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 {// 为写入的权限设置唯一idtransientInstance.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<SysAuthorities> findAuthoritiesLst(String xtmk) {try {List<SysAuthorities> 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<String,String> getSelectedResourcesMap(String authorityId) {try {List<String> 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<String,String> hashMap = new HashMap<String,String>(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<SysResources> getResourcesList() {try {return getSession().createQuery("from SysResources where enabled=1").list();} catch (RuntimeException re) {throw re;}}/** * 提取系统中的所有权限 * @return */@SuppressWarnings("unchecked")public List<String> getSysAuthorities(){String sql = "select authority_name from sys_authorities";List<String> 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<SysAuthoritiesResources,Long> implements SysAuthoritiesResourcesDao{private static final Log log = LogFactory.getLog(SysAuthoritiesResourcesDaoImpl.class);@SuppressWarnings("unchecked")public List<String> 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<SysAuthoritiesResources> getAll(){List<SysAuthoritiesResources> auths = new ArrayList<SysAuthoritiesResources>();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<SysAuthoritiesResources> findByExample(SysAuthoritiesResources instance) {log.debug("finding SysAuthoritiesResources instance by example");try {List<SysAuthoritiesResources> 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<ConfigAttributeDefinition> 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<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException{if( configAttributes == null ) {return ;}Iterator<ConfigAttribute> 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 AbstractSecurityInterceptorimplements 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);}}@Overridepublic 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方法返回的结果。 此类在初始化时,应该取到所有资源及其对应角色的定义。 *///@Servicepublic class CustomInvocationSecurityMetadataSourceService implementsFilterInvocationSecurityMetadataSource {@Autowiredprivate SysAuthoritiesDao sysAuthoritiesDao;@Autowired()private SysAuthoritiesResourcesDao sysAuthoritiesResourcesDao;private UrlMatcher urlMatcher = new AntUrlPathMatcher();private static Map<String, Collection<ConfigAttribute>> 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<String> as = sysAuthoritiesDao.getSysAuthorities();/* * 应当是资源为key, 权限为value。 资源通常为url, 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。 * aGuang */resourceMap = new HashMap<String, Collection<ConfigAttribute>>();for (String auth : as) {ConfigAttribute ca = new SecurityConfig(auth);List<String> rs = sysAuthoritiesResourcesDao.loadResource(auth);for (String url : rs) {/* * 判断资源文件和权限的对应关系,如果已经存在相关的资源url,则要通过该url为key提取出权限集合,将权限增加到权限集合中。 * aGuang */if (resourceMap.containsKey(url)) {Collection<ConfigAttribute> value = resourceMap.get(url);value.add(ca);resourceMap.put(url, value);} else {Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();atts.add(ca);resourceMap.put(url, atts);}}}}@Overridepublic Collection<ConfigAttribute> getAllConfigAttributes() {return null;}// 根据URL,找到相关的权限配置。@Overridepublic Collection<ConfigAttribute> 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<String> ite = resourceMap.keySet().iterator();while (ite.hasNext()) {String resURL = ite.next();if (urlMatcher.pathMatchesUrl(url, resURL)) {return resourceMap.get(resURL);}}return null;}@Overridepublic 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 {//用户idpublic 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<SysUsersRoles> 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 {@Autowiredprivate SysUsersDao sysUsersDao;@Overridepublic UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException {Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();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<SysUsersRoles>(0), true, true,true, auths);}public void setSysUsersDao(SysUsersDao sysUsersDao) {this.sysUsersDao = sysUsersDao;}}



主要配置:

applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsd   http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd   http://www.springframework.org/schema/tx   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd   http://www.springframework.org/schema/jee   http://www.springframework.org/schema/jee/spring-jee-3.1.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-3.1.xsd   http://www.springframework.org/schema/util    http://www.springframework.org/schema/util/spring-util-3.1.xsd"><!-- 用户的密码加密或解密 --><bean id="passwordEncoder"class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" /><!-- 定义上下文返回的消息的国际化。(新版本) 11/3/23 --><bean id="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><property name="basename"value="classpath:org/springframework/security/messages_zh_CN"/></bean><!--事件监听:实现了 ApplicationListener监听接口,包括AuthenticationCredentialsNotFoundEvent 事件,AuthorizationFailureEvent事件,AuthorizedEvent事件, PublicInvocationEvent事件。 --><beanclass="org.springframework.security.authentication.event.LoggerListener" /><!-- 用户详细信息管理:数据源、用户缓存(通过数据库管理用户、角色、权限、资源)。(新版本) 11/3/23  --><bean id="userDetailsManager" class="com.gwtjs.spring.security.CustomUserDetailsService"><property name="sysUsersDao" ref="sysUsersDao" /></bean><bean id="cacheManager"class="org.springframework.cache.CacheManager" /><!-- 启用用户的缓存功能 --><bean id="userCache"class="org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache"><property name="cache" ref="userEhCache" /></bean><bean id="userEhCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"><property name="cacheName" value="userCache" /><property name="cacheManager" ref="cacheManager" /></bean><!-- 设置权限的前缀为AUTH_,而不是ROLE_。 --><bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">    <property name="rolePrefix" value="AUTH_"/>    </bean><!-- acl(access control list)缓存管理 --><bean id="aclCache"class="org.springframework.security.acls.domain.EhCacheBasedAclCache"><constructor-arg ref="aclEhCache" /></bean><bean id="aclEhCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"><property name="cacheManager" ref="cacheManager" /><property name="cacheName" value="aclCache" /></bean></beans>



applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?><b:beans xmlns="http://www.springframework.org/schema/security"xmlns:b="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.0.xsd"><http auto-config="true" access-denied-page="/accessDenied.jsp"><!-- 不要过滤图片等静态资源 --><intercept-url pattern="/**/*.jpg" filters="none" /><intercept-url pattern="/**/*.png" filters="none" /><intercept-url pattern="/**/*.gif" filters="none" /><intercept-url pattern="/**/*.css" filters="none" /><intercept-url pattern="/**/*.js" filters="none" /><!-- 登录页面和忘记密码页面不过滤  --><intercept-url pattern="/login.jsp" filters="none" /><intercept-url pattern="/jsp/forgotpassword.jsp"filters="none" />  <form-login login-page="/login.jsp"authentication-failure-url="/login.jsp?error=true"default-target-url="/index.jsp" /><!-- "记住我"功能,采用持久化策略(将用户的登录信息存放在数据库表中) --><remember-me data-source-ref="dataSource" /><!-- 检测失效的sessionId,超时时定位到另外一个URL --><session-management invalid-session-url="/sessionTimeout.jsp" /><!-- 增加一个自定义的filter,放在FILTER_SECURITY_INTERCEPTOR之前,实现用户、角色、权限、资源的数据库管理。 11/3/23 --><custom-filter ref="customFilter" before="FILTER_SECURITY_INTERCEPTOR"/> </http><!-- 一个自定义的filter,必须包含authenticationManager,accessDecisionManager,securityMetadataSource三个属性。 11/3/23  --><b:bean id="customFilter" class="com.gwtjs.spring.security.CustomFilterSecurityInterceptor"><b:property name="authenticationManager" ref="authenticationManager"/><b:property name="accessDecisionManager" ref="customAccessDecisionManager"/><b:property name="securityMetadataSource" ref="customSecurityMetadataSource"/></b:bean><!-- 注意能够为authentication-manager 设置alias别名  --><authentication-manager alias="authenticationManager"><authentication-provider user-service-ref="userDetailsManager"><password-encoder ref="passwordEncoder"><salt-source user-property="username" /></password-encoder></authentication-provider></authentication-manager><!-- 访问决策器,决定某个用户具有的角色,是否有足够的权限去访问某个资源。11/3/23 --><b:bean id="customAccessDecisionManager"class="com.gwtjs.spring.security.CustomAccessDecisionManager"></b:bean>  <!-- 资源源数据定义,将所有的资源和权限对应关系建立起来,即定义某一资源可以被哪些角色去访问。11/3/23 --><b:bean id="customSecurityMetadataSource"class="com.gwtjs.spring.security.CustomInvocationSecurityMetadataSourceService"></b:bean> </b:beans>



下一篇:

使用Junit Test探究对象关系



原创粉丝点击