简介:spring security 实现的权限控制,可以分别保护后台方法的管理,url连接访问的控制,以及页面元素的权限控制等,
security的保护,配置有简单到复杂基本有三部:
1) 采用硬编码的方式:具体做法就是在security.xml文件中,将用户以及所拥有的权限写死,一般是为了查看环境搭建的检查状态.
2) 数据库查询用户以及权限的方式,这种方式就是在用户的表中直接存入了权限的信息,比如 role_admin,role_user这样的权限信息,取出来的时候,再将其拆分.
3) 角色权限动态配置,这种方式值得是将权限角色单独存入数据库中,与用户进行相关联,然后进行相应的设置.
下面就这三种方式进行相应的程序解析
新建web项目,导入其中的包,环境搭建就算是完了,下面一部我们开始security权限控制中方法的第一种.
contextConfigLocation
/WEB-INF/security/*.xml
org.springframework.web.context.ContextLoaderListener
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/security/dispatcher-servlet.xml
1
dispatcher
*.do
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
/*
下面我们就开始配置mvc的配置文件,名称为dispatcher-servlet.xml的springmvc的配置文件内容如下:
下一步,我们开始讲解第二种,数据库的用户登陆并实现获取权限进行操作.
CREATE TABLE `user` (
`Id` int(11) NOT NULL auto_increment,
`logname` varchar(255) default NULL,
`password` varchar(255) default NULL,
`role_ids` varchar(255) default NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
登录界面
登录界面
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form" %>
Insert title here
logout
显示拥有ROLE_USER权限的页面
测试方法控制访问权限
添加报表管理员
删除报表管理员
package com.ucs.security.server;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ucs.security.face.SecurityTestInterface;
@Controller
public class SecurityTest {
@Resource
private SecurityTestInterface dao;
@RequestMapping(value="/jsp/getinput")//查看最近收入
@ResponseBody
public boolean getinput(HttpServletRequest req,HttpServletRequest res){
boolean b=dao.getinput();
return b;
}
@RequestMapping(value="/jsp/geoutput")//查看最近支出
@ResponseBody
public boolean geoutput(HttpServletRequest req,HttpServletRequest res){
boolean b=dao.geoutput();
return b;
}
@RequestMapping(value="/jsp/addreport_admin")//添加报表管理员
@ResponseBody
public boolean addreport_admin(HttpServletRequest req,HttpServletRequest res){
boolean b=dao.addreport_admin();
return b;
}
@RequestMapping(value="/jsp/deletereport_admin")//删除报表管理员
@ResponseBody
public boolean deletereport_admin(HttpServletRequest req,HttpServletRequest res){
boolean b=dao.deletereport_admin();
return b;
}
@RequestMapping(value="/jsp/user")//普通用户登录
public ModelAndView user_login(HttpServletRequest req,HttpServletRequest res){
dao.user_login();
return new ModelAndView("user");
}
}
package com.ucs.security.face;
import javax.annotation.security.RolesAllowed;
import com.ucs.security.pojo.Users;
public interface SecurityTestInterface {
boolean getinput();
boolean geoutput();
@RolesAllowed("ROLE_ADMIN")//拥有ROLE_ADMIN权限的用户才可进入此方法
boolean addreport_admin();
@RolesAllowed("ROLE_ADMIN")
boolean deletereport_admin();
Users findbyUsername(String name);
@RolesAllowed("ROLE_USER")
void user_login();
}
package com.ucs.security.dao;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.ucs.security.face.SecurityTestInterface;
import com.ucs.security.pojo.Users;
@Repository("SecurityTestDao")
public class SecurityTestDao implements SecurityTestInterface{
Logger log=Logger.getLogger(SecurityTestDao.class);
@Resource
private JdbcTemplate jdbcTamplate;
public boolean getinput() {
log.info("getinput");
return true;
}
public boolean geoutput() {
log.info("geoutput");
return true;
}
public boolean addreport_admin() {
log.info("addreport_admin");
return true;
}
public boolean deletereport_admin() {
log.info("deletereport_admin");
return true;
}
public Users findbyUsername(String name) {
final Users users = new Users();
jdbcTamplate.query("SELECT * FROM USER WHERE logname = ?",
new Object[] {name},
new RowCallbackHandler() {
@Override
public void processRow(java.sql.ResultSet rs)
throws SQLException {
users.setName(rs.getString("logname"));
users.setPassword(rs.getString("password"));
users.setRole(rs.getString("role_ids"));
}
});
log.info(users.getName()+" "+users.getPassword()+" "+users.getRole());
return users;
}
@Override
public void user_login() {
log.info("拥有ROLE_USER权限的方法访问:user_login");
}
}
package com.ucs.security.context;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ucs.security.face.SecurityTestInterface;
import com.ucs.security.pojo.Users;
/**
* 在spring-security.xml中如果配置了
*
* 将会使用这个类进行权限的验证。
*
* **/
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService{
@Resource
private SecurityTestInterface dao;
//登录验证
public UserDetails loadUserByUsername(String name)
throws UsernameNotFoundException {
System.out.println("show login name:"+name+" ");
Users users =dao.findbyUsername(name);
Set grantedAuths=obtionGrantedAuthorities(users);
boolean enables = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
//封装成spring security的user
User userdetail = new User(users.getName(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
return userdetail;
}
//查找用户权限
public Set obtionGrantedAuthorities(Users users){
String roles[] = users.getRole().split(",");
Set authSet=new HashSet();
for (int i = 0; i < roles.length; i++) {
authSet.add(new GrantedAuthorityImpl(roles[i]));
}
return authSet;
}
}
登录的时候获取登录的用户名,然后通过数据库去查找该用户拥有的权限将权限增加到Set
点击添加报表管理员或者删除报表管理员时候会跳到403.jsp因为没有权限去访问资源,在接口上我们设置了访问的权限:
下面我们就开始研究第三种方式,需要用将角色可访问资源链接保存到数据库,可以随时更改,也就是我们所谓的url的控制,什么鸡毛,就是数据库存放了角色权限,可以实时更改,而不再xml文件中写死.
下面链接,我给大家提供了一个源码的下载链接 , 这是本届讲解的内容的源码,运行无误,狼心货 http://download.csdn.net/detail/u014201191/8929187
# Host: localhost (Version: 5.0.22-community-nt)
# Date: 2014-03-28 14:58:01
# Generator: MySQL-Front 5.3 (Build 4.81)
/*!40101 SET NAMES utf8 */;
#
# Structure for table "power"
#
DROP TABLE IF EXISTS `power`;
CREATE TABLE `power` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`power_name` VARCHAR(255) DEFAULT NULL,
`resource_ids` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
#
# Data for table "power"
#
INSERT INTO `power` VALUES (1,'查看报表','1,2,'),(2,'管理系统','3,4,');
#
# Structure for table "resource"
#
DROP TABLE IF EXISTS `resource`;
CREATE TABLE `resource` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`resource_name` VARCHAR(255) DEFAULT NULL,
`resource_url` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
#
# Data for table "resource"
#
INSERT INTO `resource` VALUES (1,'查看最近收入','/jsp/getinput.do'),(2,'查看最近支出','/jsp/geoutput.do'),(3,'添加报表管理员','/jsp/addreport_admin.do'),(4,'删除报表管理员','/jsp/deletereport_admin.do');
#
# Structure for table "role"
#
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`role_name` VARCHAR(255) DEFAULT NULL,
`role_type` VARCHAR(255) DEFAULT NULL,
`power_ids` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
#
# Data for table "role"
#
INSERT INTO `role` VALUES (1,'系统管理员','ROLE_ADMIN','1,2,'),(2,'报表管理员','ROLE_USER','1,');
#
# Structure for table "user"
#
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`Id` INT(11) NOT NULL AUTO_INCREMENT,
`logname` VARCHAR(255) DEFAULT NULL,
`password` VARCHAR(255) DEFAULT NULL,
`role_ids` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
SELECT * FROM USER;
#
# Data for table "user"
#
INSERT INTO `user` VALUES (1,'admin','123456','ROLE_USER,ROLE_ADMIN'),(3,'zhang','123','ROLE_USER');
COMMIT;
package com.ucs.security.context;
import java.util.Collection;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
@Service("myAccessDecisionManager")
public class MyAccessDecisionManager implements AccessDecisionManager{
Logger log=Logger.getLogger(MyAccessDecisionManager.class);
@Override
public void decide(Authentication authentication, Object object,
Collection configAttributes) throws AccessDeniedException,
InsufficientAuthenticationException {
// TODO Auto-generated method stub
//如果对应资源没有找到角色 则放行
if(configAttributes == null){
return ;
}
log.info("object is a URL:"+object.toString()); //object is a URL.
Iterator ite=configAttributes.iterator();
while(ite.hasNext()){
ConfigAttribute ca=ite.next();
String needRole=ca.getAttribute();
for(GrantedAuthority ga:authentication.getAuthorities()){
if(needRole.equals(ga.getAuthority())){ //ga is user's role.
return;
}
}
}
throw new AccessDeniedException("no right");
}
@Override
public boolean supports(ConfigAttribute arg0) {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean supports(Class> arg0) {
// TODO Auto-generated method stub
return true;
}
}
package com.ucs.security.context;
import java.io.IOException;
import javax.annotation.Resource;
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.apache.log4j.Logger;
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;
public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {
Logger log=Logger.getLogger(MySecurityFilter.class);
private FilterInvocationSecurityMetadataSource securityMetadataSource;
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
}
public void setSecurityMetadataSource(
FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
FilterInvocation fi=new FilterInvocation(req,res,chain);
log.info("--------MySecurityFilter--------");
invok(fi);
}
private void invok(FilterInvocation fi) throws IOException, ServletException {
// object为FilterInvocation对象
//1.获取请求资源的权限
//执行Collection attributes = SecurityMetadataSource.getAttributes(object);
//2.是否拥有权限
//获取安全主体,可以强制转换为UserDetails的实例
//1) UserDetails
// Authentication authenticated = authenticateIfRequired();
//this.accessDecisionManager.decide(authenticated, object, attributes);
//用户拥有的权限
//2) GrantedAuthority
//Collection authenticated.getAuthorities()
log.info("用户发送请求! ");
InterceptorStatusToken token = null;
token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
public Class extends Object> getSecureObjectClass() {
//下面的MyAccessDecisionManager的supports方面必须放回true,否则会提醒类型错误
return FilterInvocation.class;
}
}
package com.ucs.security.context;
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 java.util.Set;
import java.util.Map.Entry;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
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.stereotype.Service;
import com.google.gson.Gson;
import com.ucs.security.face.SecurityTestInterface;
import com.ucs.security.pojo.URLResource;
@Service("mySecurityMetadataSource")
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource{
//由spring调用
Logger log=Logger.getLogger(MySecurityMetadataSource.class);
@Resource
private SecurityTestInterface dao;
private static Map> resourceMap = null;
/*public MySecurityMetadataSource() {
loadResourceDefine();
}*/
public Collection getAllConfigAttributes() {
// TODO Auto-generated method stub
return null;
}
public boolean supports(Class> clazz) {
// TODO Auto-generated method stub
return true;
}
//加载所有资源与权限的关系
private void loadResourceDefine() {
if(resourceMap == null) {
resourceMap = new HashMap>();
/*List resources ;
resources = Lists.newArrayList("/jsp/user.do","/jsp/getoutput.do");*/
List findResources = dao.findResource();
for(URLResource url_resource:findResources){
Collection configAttributes = new ArrayList();
ConfigAttribute configAttribute = new SecurityConfig(url_resource.getRole_Name());
for(String resource:url_resource.getRole_url()){
configAttributes.add(configAttribute);
resourceMap.put(resource, configAttributes);
}
}
//以权限名封装为Spring的security Object
}
Gson gson =new Gson();
log.info("权限资源对应关系:"+gson.toJson(resourceMap));
Set>> resourceSet = resourceMap.entrySet();
Iterator>> iterator = resourceSet.iterator();
}
//返回所请求资源所需要的权限
public Collection getAttributes(Object object) throws IllegalArgumentException {
String requestUrl = ((FilterInvocation) object).getRequestUrl();
log.info("requestUrl is " + requestUrl);
if(resourceMap == null) {
loadResourceDefine();
}
log.info("通过资源定位到的权限:"+resourceMap.get(requestUrl));
return resourceMap.get(requestUrl);
}
}
package com.ucs.security.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.ucs.security.face.SecurityTestInterface;
import com.ucs.security.pojo.URLResource;
import com.ucs.security.pojo.Users;
@Repository("SecurityTestDao")
public class SecurityTestDao implements SecurityTestInterface{
Logger log=Logger.getLogger(SecurityTestDao.class);
@Resource
private JdbcTemplate jdbcTamplate;
public boolean getinput() {
log.info("getinput");
return true;
}
public boolean geoutput() {
log.info("geoutput");
return true;
}
public boolean addreport_admin() {
log.info("addreport_admin");
return true;
}
public boolean deletereport_admin() {
log.info("deletereport_admin");
return true;
}
public Users findbyUsername(String name) {
final Users users = new Users();
jdbcTamplate.query("SELECT * FROM USER WHERE logname = ?",
new Object[] {name},
new RowCallbackHandler() {
@Override
public void processRow(java.sql.ResultSet rs)
throws SQLException {
users.setName(rs.getString("logname"));
users.setPassword(rs.getString("password"));
users.setRole(rs.getString("role_ids"));
}
});
log.info(users.getName()+" "+users.getPassword()+" "+users.getRole());
return users;
}
@Override
public void user_login() {
log.info("拥有ROLE_USER权限的方法访问:user_login");
}
@Override
//获取所有资源链接
public List findResource() {
List uRLResources =Lists.newArrayList();
Map role_types=new HashMap();
List role_Names=Lists.newArrayList();
List list_role=jdbcTamplate.queryForList("select role_type,power_ids from role");
Iterator it_role = list_role.iterator();
while(it_role.hasNext()){
Map role_map=(Map)it_role.next();
String object = (String)role_map.get("power_ids");
String type = (String)role_map.get("role_type");
role_Names.add(type);
String[] power_ids = object.split(",");
Integer[] int_pow_ids=new Integer[power_ids.length];
for(int i=0;i all_res_ids=Lists.newArrayList();
List urls=Lists.newArrayList();
for(Integer id:ids){//更具权限id获取资源id
List resource_ids=jdbcTamplate.queryForList("select resource_ids from power where id =?",new Object[]{id});
Iterator it_resource_ids = resource_ids.iterator();
while(it_resource_ids.hasNext()){
Map resource_ids_map=(Map)it_resource_ids.next();
String[] ids_str=((String)resource_ids_map.get("resource_ids")).split(",");
for(int i=0;i
package com.ucs.security.face;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import com.ucs.security.pojo.URLResource;
import com.ucs.security.pojo.Users;
public interface SecurityTestInterface {
boolean getinput();
boolean geoutput();
//@RolesAllowed("ROLE_ADMIN")//拥有ROLE_ADMIN权限的用户才可进入此方法
boolean addreport_admin();
//@RolesAllowed("ROLE_ADMIN")
boolean deletereport_admin();
Users findbyUsername(String name);
//@RolesAllowed("ROLE_USER")
void user_login();
List findResource();
}