集成spring security3.0权限控制

   最近在一个项目中使用权限控制,由于之前使用的是spring acegi 感觉还不错挺好用但这个版本比较老了,所以就研究了一下最新版本的spring security3.0,目前3.0的网上的相关文档及其至少(官方中的3.0文档资料有很多都是spring security2.*的),遂把自己的这几天研究的成果拿出来与大家分享。希望对大家有所帮助!

 

   首先现在数据库中创建一些数据库脚本(本例数据库采用的是Oracle,需根据个人所使用的数据库进行更改相应的数据类型):

 

CREATE TABLE resources (
  id int NOT NULL primary key,
  type varchar2(255),
  value varchar2(255)
) ;

insert  into resources(id,type,value) values (1,'URL','/**');

 

CREATE TABLE role (
  id int NOT NULL,
  name varchar2(255),
  description varchar2(255),
  PRIMARY KEY  (id)
);

insert  into role(id,name,description) values (1,'ROLE_USER','ROLE_USER'),(2,'ROLE_ADMIN','ROLE_ADMIN');

 

CREATE TABLE role_resources (
  role_id int NOT NULL,
  resource_id int NOT NULL,
  PRIMARY KEY  (role_id,resource_id),
  CONSTRAINT FKAEE599B751827FA1 FOREIGN KEY (role_id) REFERENCES role (id),
  CONSTRAINT FKAEE599B7EFD18D21 FOREIGN KEY (resource_id) REFERENCES resources (id)
) ;

insert  into role_resources(role_id,resource_id) values (1,1),(2,1);

 

CREATE TABLE users (
  id int NOT NULL PRIMARY KEY ,
  name varchar2(255) default NULL,
  password varchar2(255) default NULL,
  disabled int NOT NULL
);

insert  into users(id,name,password,disabled) values (1,'fzt','21232f297a57a5a743894a0e4a801fc3',0),(2,'Victor','21232f297a57a5a743894a0e4a801fc3',0);

 

CREATE TABLE user_role (
  user_id int NOT NULL,
  role_id int NOT NULL,
  PRIMARY KEY  (user_id,role_id),
  CONSTRAINT FK143BF46A51827FA1 FOREIGN KEY (role_id) REFERENCES role (id),
  CONSTRAINT FK143BF46AF6AD4381 FOREIGN KEY (user_id) REFERENCES users (id)
);

insert  into user_role(user_id,role_id) values (1,1),(1,2),(2,1);

注:用户表中的密码为admin

 

以下是model类模型:

User.java

package com.xindun.axt.model;

 

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Proxy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * <p>Title: an User.java file of the portal project. </p>
 * <p>Description: 获取用户信息</p>
 * <p>Create Time: 2009-11-6 下午02:10:34 </p>
 * <p>Company: ×× Network Tech Co., Ltd</p>
 * @author Victor Von

 * @version 1.0
 */
@Entity
@Proxy(lazy = false)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(uniqueConstraints={}, name="users")
public class User implements UserDetails {
 
 private static final long serialVersionUID = 8026813053768023527L;
 
 @SequenceGenerator(name="SEQ_USER",sequenceName="seq_user",allocationSize=1)
    @Id
 @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="SEQ_USER")
 private Integer id;
 
 private String name;
 
 private String password;
 /** 是否正常使用  0为已禁止 1为正常使用 */
 private int disabled;
 
 @ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
 private Set<Role> roles;
 
 @Transient
 private Map<String, List<Resource>> roleResources;
 
 /**
  * The default constructor
  */
 public User() {
  
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#getAuthorities()
  */
 public Collection<GrantedAuthority> getAuthorities() {
  Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());
     for(Role role : roles) {
      grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));
     }
        return grantedAuthorities;
 }
 
 /**
  * Returns the authorites string
  *
  * eg.
  *    downpour --- ROLE_ADMIN,ROLE_USER
  *    robbin --- ROLE_ADMIN
  *
  * @return
  */
 public String getAuthoritiesString() {
     List<String> authorities = new ArrayList<String>();
     for(GrantedAuthority authority : this.getAuthorities()) {
         authorities.add(authority.getAuthority());
     }
     return StringUtils.join(authorities, ",");
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#getPassword()
  */
 public String getPassword() {
  return password;
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#getUsername()
  */
 public String getUsername() {
  return name;
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired()
  */
 public boolean isAccountNonExpired() {
  return true;
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked()
  */
 public boolean isAccountNonLocked() {
  return true;
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired()
  */
 public boolean isCredentialsNonExpired() {
  return true;
 }

 /* (non-Javadoc)
  * @see org.springframework.security.userdetails.UserDetails#isEnabled()
  */
 public boolean isEnabled() {
  return (disabled==1?true:false);
 }

 /**
  * @return the id
  */
 public Integer getId() {
  return id;
 }

 /**
  * @return the name
  */
 public String getName() {
  return name;
 }

 /**
  * @return the disabled
  */
 public int getDisabled() {
  return disabled;
 }

 /**
  * @return the roles
  */
 public Set<Role> getRoles() {
  return roles;
 }

 /**
  * @return the roleResources
  */
 public Map<String, List<Resource>> getRoleResources() {
  // init roleResources for the first time
  if(this.roleResources == null) {
   
   this.roleResources = new HashMap<String, List<Resource>>();
   
   for(Role role : this.roles) {
    String roleName = role.getName();
    Set<Resource> resources = role.getResources();
    for(Resource resource : resources) {
     String key = roleName + "_" + resource.getType();
     if(!this.roleResources.containsKey(key)) {
      this.roleResources.put(key, new ArrayList<Resource>());
     }
     this.roleResources.get(key).add(resource);     
    }
   }
   
  }
  return this.roleResources;
 }

 /**
  * @param id the id to set
  */
 public void setId(Integer id) {
  this.id = id;
 }

 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }

 /**
  * @param password the password to set
  */
 public void setPassword(String password) {
  this.password = password;
 }

 /**
  * @param disabled the disabled to set
  */
 public void setDisabled(int disabled) {
  this.disabled = disabled;
 }

 /**
  * @param roles the roles to set
  */
 public void setRoles(Set<Role> roles) {
  this.roles = roles;
 }
 
}

 

 

由于浏览器的问题代码不能使用 CSDN的“插入代码”功能(导致界面贴太多代码太难看懂  :) ),所以等项目开发完后再一一贴出或整理一下打包传上来,如有急需的朋友,可以留言。

 

例子下载地址:

 

你可能感兴趣的:(集成spring security3.0权限控制)