spring security 3.1 实现权限控制

Posted slgkaifa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring security 3.1 实现权限控制相关的知识,希望对你有一定的参考价值。

spring security 3.1 实现权限控制



简单介绍:spring security 实现的权限控制,能够分别保护后台方法的管理,url连接訪问的控制,以及页面元素的权限控制等,

        security的保护,配置有简单到复杂基本有三部:

         1) 採用硬编码的方式:详细做法就是在security.xml文件里,将用户以及所拥有的权限写死,通常是为了查看环境搭建的检查状态.

         2) 数据库查询用户以及权限的方式,这种方式就是在用户的表中直接存入了权限的信息,比方 role_admin,role_user这种权限信息,取出来的时候,再将其拆分.

         3) 角色权限动态配置,这样的方式值得是将权限角色单独存入数据库中,与用户进行相关联,然后进行对应的设置.

            以下就这三种方式进行对应的程序解析


初始化环境搭建

在本文中提供了全部程序中的jar下载地址:
http://download.csdn.net/detail/u014201191/8928943

新建web项目,导入当中的包,环境搭建就算是完了,以下一部我们開始security权限控制中方法的第一种.


硬编码配置

第一步首先是web.xml文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	
	
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/security/*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
  	<servlet>
  		<servlet-name>dispatcher</servlet-name>
  		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/security/dispatcher-servlet.xml</param-value>
  		</init-param>
  		<load-on-startup>1</load-on-startup>
  	</servlet>
  	<servlet-mapping>
  		<servlet-name>dispatcher</servlet-name>
  		<url-pattern>*.do</url-pattern>
  	</servlet-mapping>
 <!-- 权限 -->  
  	 <filter>
 		 <filter-name>springSecurityFilterChain</filter-name>
		 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  	 </filter>

	<filter-mapping>
	  <filter-name>springSecurityFilterChain</filter-name>
	  <url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

security的权限控制是基于springMvc的,所以在当中要配置,而对于权限的控制名字是有特别的含义的,不可更改.


以下我们就開始配置mvc的配置文件,名称为dispatcher-servlet.xml的springmvc的配置文件内容例如以下:

<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 使Spring支持自己主动检測组件,如注解的Controller --> <context:component-scan base-package="com"/> <aop:aspectj-autoproxy/> <!-- 开启AOP --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list > <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> <!-- 数据库连接配置 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/power"></property> <property name="user" value="root"></property> <property name="password" value="516725"></property> <property name="minPoolSize" value="10"></property> <property name="MaxPoolSize" value="50"></property> <property name="MaxIdleTime" value="60"></property><!-- 最少空暇连接 --> <property name="acquireIncrement" value="5"></property><!-- 当连接池中的连接耗尽的时候 c3p0一次同一时候获取的连接数。

--> <property name="TestConnectionOnCheckout" value="true" ></property> </bean> <bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref local="dataSource"/> </property> </bean> <!-- 事务申明 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" > <ref local="dataSource"/> </property> </bean> <!-- Aop切入点 --> <aop:config> <aop:pointcut expression="within(com.ucs.security.dao.*)" id="serviceOperaton"/> <aop:advisor advice-ref="txadvice" pointcut-ref="serviceOperaton"/> </aop:config> <tx:advice id="txadvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> </beans>


下一步我们開始配置spring-securoty.xml的权限控制配置,例如以下:

<?

xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- 对全部页面进行拦截。须要ROLE_USER权限 --> <http auto-config='true'> <intercept-url pattern="/**" access="ROLE_USER" /> </http> <!-- 权限配置 jimi拥有两种权限 bob拥有一种权限 --> <authentication-manager> <authentication-provider> <user-service> <user name="jimi" password="123" authorities="ROLE_USER, ROLE_ADMIN" /> <user name="bob" password="456" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>


到此为止,权限的配置基本就结束了,以下就启动服务,securoty会为我们自己主动生成一个登陆页面,在地址栏中输入:http://localhost:8080/项目名称/spring_security_login,会出现一个登陆界面,尝试一下吧.看看登陆以后能不能依照你的权限配置进行控制.

下一步,我们開始解说另外一种,数据库的用户登陆并实现获取权限进行操作.

数据库权限控制


首先第一步我们開始建表,使用的数据库是mysql.

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;

我们改动spring-security.xml文件,让其不在写死这些权限和用户的控制:

<?

xml version="1.0" encoding="UTF-8"?

> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- 启用方法控制訪问权限 用于直接拦截接口上的方法。拥有权限才干訪问此方法--> <global-method-security jsr250-annotations="enabled"/> <!-- 自己写登录页面,而且登陆页面不拦截 --> <http pattern="/jsp/login.jsp" security="none" /> <!-- 配置拦截页面 --> <!-- 启用页面级权限控制 使用表达式 --> <http auto-config='true' access-denied-page="/jsp/403.jsp" use-expressions="true"> <intercept-url pattern="/**" access="hasRole('ROLE_USER')" /> <!-- 设置用户默认登录页面 --> <form-login login-page="/jsp/login.jsp"/> </http> <authentication-manager> <!-- 权限控制 引用 id是myUserDetailsService的server --> <authentication-provider user-service-ref="myUserDetailsService"/> </authentication-manager> </beans:beans>


以下编辑了自己的登陆页面,我们做一个解释:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录界面</title>
</head>
<body>
	<h3>登录界面</h3>
	
		<form action="/项目根文件夹/j_spring_security_check" method="post">
			<table>
			    <tr><td>User:</td><td><input type='text' name='j_username' value=''></td></tr>
			    <tr><td>Password:</td><td><input type='password' name='j_password'/></td></tr>
			    <tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
			</table>
		</form>
	
</body>
</html>

再次,我们做一个解释啊,登陆页面中的字段的名称不能更改,而注意上面的链接,这个链接的请求地址直接就指向了在上面的xml文件里配置的myUserDetailsService这个类中的请求方法.

以下我们提供一个user.jsp的页面,来展示我们有权限的才干进入这个页面,并且这个页面上海提供了页面元素的权限控制,通过标签实现了这种控制.user页面是ROLE_USER权限界面,当中引用了security标签。在配置文件里 use-expressions="true"代表启用页面控制语言,就是依据不同的权限页面显示该权限应该显示的内容。假设查看网页源码也是看不到初自己权限以外的内容的。

<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; utf-8">
<title>Insert title here</title>
</head>
<body>
	<h5><a href="../j_spring_security_logout">logout</a></h5>
	<!-- 拥有ROLE_ADMIN权限的才看的到 -->
	<sec:authorize access="hasRole('ROLE_ADMIN')">
	<form action="#">
		账号:<input type="text" /><br/>
		密码:<input type="password"/><br/>
		<input type="submit" value="submit"/>
	</form>
	</sec:authorize>
	
	<p/>
	<sec:authorize access="hasRole('ROLE_USER')">
	显示拥有ROLE_USER权限的页面<br/>
	<form action="#">
		账号:<input type="text" /><br/>
		密码:<input type="password"/><br/>
		<input type="submit" value="submit"/>
	</form>
	
	</sec:authorize>
	<p/>
	<h5>測试方法控制訪问权限</h5>
	<a href="addreport_admin.do">加入报表管理员</a><br/>
	<a href="deletereport_admin.do">删除报表管理员</a>
</body>
</html>

以下展示的是訪问controller层

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");
	}
	
}

我们再次写入了一个内部方法调用的接口,这个我们能够使用权限进行方法的保护,在配置文件里<global-method-security jsr250-annotations="enabled"/>就是在接口上设置权限,当拥有权限时才干调用方法,没有权限是不能调用方法的,保证了安全性

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"); } }


以下就是重要的一个类:MyUserDetailsService这个类须要去实现UserDetailsService这个接口:


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中假设配置了
 * <authentication-manager>
		<authentication-provider user-service-ref="myUserDetailsService" />
  </authentication-manager>
 * 将会使用这个类进行权限的验证。

* * **/ @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<GrantedAuthority> 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<GrantedAuthority> obtionGrantedAuthorities(Users users){ String roles[] = users.getRole().split(","); Set<GrantedAuthority> authSet=new HashSet<GrantedAuthority>(); for (int i = 0; i < roles.length; i++) { authSet.add(new GrantedAuthorityImpl(roles[i])); } return authSet; } }

登录的时候获取登录的username,然后通过数据库去查找该用户拥有的权限将权限添加到Set<GrantedAuthority>中,当然能够加多个权限进去,仅仅要用户拥有当中一个权限就能够登录进来。
然后将从数据库查到的password和权限设置到security自己的User类中。security会自己去匹配前端发来的password和用户权限去对照。然后推断用户能否够登录进来。登录失败还是停留在登录界面。

在user.jsp中測试了用户权限来验证能否够拦截没有权限用户去訪问资源:

技术分享

点击加入报表管理员或者删除报表管理员时候会跳到403.jsp由于没有权限去訪问资源。在接口上我们设置了訪问的权限:

[java] view plaincopy技术分享技术分享
  1. @RolesAllowed("ROLE_ADMIN")//拥有ROLE_ADMIN权限的用户才可进入此方法  
  2.     boolean addreport_admin();  
  3.     @RolesAllowed("ROLE_ADMIN")  
  4.     boolean deletereport_admin();  

由于登录进来的用户时ROLE_USER权限的。

就被拦截下来。

logout是登出,返回到登录界面。而且用户在security中的缓存清掉了。一样会对资源进行拦截。



以下我们就開始研究第三种方式,须要用将角色可訪问资源链接保存到数据库,能够随时更改,也就是我们所谓的url的控制,什么鸡毛,就是数据库存放了角色权限,能够实时更改,而不再xml文件里写死.

以下链接,我给大家提供了一个源代码的下载链接 , 这是本届解说的内容的源代码,执行无误,狼心货 http://download.csdn.net/detail/u014201191/8929187


角色权限管理


開始,我们先来一个对照,上面的方法每种地址都要在配置文件里写入,这样太死板了,我们这个角色权限的管理,针对的就是URL的控制,在数据库中将訪问URL和角色关联,上一种方法中,没有所谓的URl控制,仅仅是方法级别的控制,这次我们将直接控制URL.

首先我们给出一个数据库的配置文件,也即是sql运行脚本,帮助大家建表我存入数据:

# 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;

以下我们就開始写入spring-security.xml的配置文件:

<?

xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- 启用方法控制訪问权限 用于直接拦截接口上的方法。拥有权限才干訪问此方法--> <global-method-security jsr250-annotations="enabled"/> <!-- 自己写登录页面。而且登陆页面不拦截 --> <http pattern="/jsp/login.jsp" security="none" /> <!-- 配置拦截页面 --> <!-- 启用页面级权限控制 使用表达式 --> <http auto-config='true' access-denied-page="/jsp/403.jsp" use-expressions="true"> <!-- requires-channel="any" 设置訪问类型http或者https --> <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/> <!-- intercept-url pattern="/admin/**" 拦截地址的设置有载入先后的顺序, admin/**在前面请求admin/admin.jsp会先去拿用户验证是否有ROLE_ADMIN权限。有则通过,没有就拦截。假设shi pattern="/**" 设置在前面,当前登录的用户有ROLE_USER权限。那么就能够登录到admin/admin.jsp 所以两个配置有先后的。 --> <intercept-url pattern="/**" access="hasRole('ROLE_USER')" requires-channel="any"/> <!-- 设置用户默认登录页面 --> <form-login login-page="/jsp/login.jsp"/> <!-- 基于url的权限控制,载入权限资源管理拦截器,假设进行这种设置,那么 <intercept-url pattern="/admin/**" 就能够不进行配置了,会在数据库的资源权限中得到相应。 对于没有找到资源的权限为null的值就不须要登录才干够查看,相当于public的。能够公共訪问 --> <custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR"/> </http> <!-- 当基于方法权限控制的时候仅仅须要此配置,在接口上加上权限就可以控制方法的调用 <authentication-manager> <authentication-provider user-service-ref="myUserDetailsService"/> </authentication-manager> --> <!-- 资源权限控制 --> <beans:bean id="securityFilter" class="com.ucs.security.context.MySecurityFilter"> <!-- 用户拥有的权限 --> <beans:property name="authenticationManager" ref="myAuthenticationManager" /> <!-- 用户是否拥有所请求资源的权限 --> <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" /> <!-- 资源与权限相应关系 --> <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" /> </beans:bean> <authentication-manager alias="myAuthenticationManager"> <!-- 权限控制 引用 id是myUserDetailsService的server --> <authentication-provider user-service-ref="myUserDetailsService"/> </authentication-manager> </beans:beans>


同一时候,我们添加在xml文件里配置的java类:

MyAccessDecisionManager这个类。就是获取到请求资源的角色后推断用户是否有这个权限能够訪问这个资源。

假设获取到的角色是null,那就放行通过,这主要是对于那些不须要验证的公共能够訪问的方法。就不须要权限了。

能够直接訪问。


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<ConfigAttribute> 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<ConfigAttribute> 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;
	}

}

在http标签中加入了:<custom-filter ref="securityFilter" before="FILTER_SECURITY_INTERCEPTOR"/>,用于地址的拦截
MySecurityFilter这个类是拦截中一个基本的类,拦截的时候会先通过这里:

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<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);
		//2.是否拥有权限
		//获取安全主体。能够强制转换为UserDetails的实例
		//1) UserDetails
		// Authentication authenticated = authenticateIfRequired();
		//this.accessDecisionManager.decide(authenticated, object, attributes);
		//用户拥有的权限
		//2) GrantedAuthority
		//Collection<GrantedAuthority> 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;
	}
	

}

MySecurityMetadataSource这个类是查找和匹配全部角色的资源相应关系的,通过訪问一个资源,能够得到这个资源的角色。返货给下一个类MyAccessDecisionManager去推断是够能够放行通过验证。

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<String, Collection<ConfigAttribute>> resourceMap = null;

	/*public MySecurityMetadataSource() {
		
		loadResourceDefine();
	}*/
	

	public Collection<ConfigAttribute> 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<String, Collection<ConfigAttribute>>(); /*List<String> resources ; resources = Lists.newArrayList("/jsp/user.do","/jsp/getoutput.do");*/ List<URLResource> findResources = dao.findResource(); for(URLResource url_resource:findResources){ Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>(); 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<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet(); Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator(); } //返回所请求资源所须要的权限 public Collection<ConfigAttribute> 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); } }


dao类中的方法有所改变:

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<URLResource> findResource() { List<URLResource> uRLResources =Lists.newArrayList(); Map<String,Integer[]> role_types=new HashMap<String, Integer[]>(); List<String> 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<power_ids.length;i++){ int_pow_ids[i]=Integer.parseInt(power_ids[i]); } role_types.put(type, int_pow_ids); } for(String name:role_Names){ URLResource resource=new URLResource(); Integer[] ids=role_types.get(name);//更具角色获取权限id List<Integer> all_res_ids=Lists.newArrayList(); List<String> 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<ids_str.length;i++){ all_res_ids.add(Integer.parseInt(ids_str[i])); } } } for(Integer id:all_res_ids){ List resource_urls=jdbcTamplate.queryForList("select resource_url from resource where id=?

",new Object[]{id}); Iterator it_res_urls = resource_urls.iterator(); while(it_res_urls.hasNext()){ Map res_url_map=(Map)it_res_urls.next(); urls.add(((String)res_url_map.get("resource_url"))); } } //将相应的权限关系加入到URLRsource resource.setRole_Name(name); resource.setRole_url(urls); uRLResources.add(resource); } Gson gson =new Gson(); log.info("权限资源相应关系:"+gson.toJson(uRLResources)); return uRLResources; } }


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<URLResource> findResource();

}

假设项目中有错误或者别的,就是缺少了pojo等,前去如今就好了,注意在src下存放一个log4j的properties的配置文件,完美了

本届的解说我给大家一个源代码的下载链接, 如有须要的请前去下载就可以,有不论什么疑问能够给我留言,谢谢:
http://download.csdn.net/detail/u014201191/8929223

security的权限控制小总结

首先用户没有登录的时候能够訪问一些公共的资源,可是必须把<intercept-url pattern="/**" access="hasRole(‘ROLE_USER‘)" requires-channel="any"/> 配置删掉。不拦截,不论什么资源都能够訪问。这样公共资源能够随意訪问。

对于须要权限的资源已经在数据库配置。假设去訪问会直接跳到登录界面。须要登录。



依据登录用户不同分配到的角色就不一样,依据角色不同来获取该角色能够訪问的资源。

拥有ROLE_USER角色用户去訪问ROLE_ADMIN的资源会返回到403.jsp页面。拥有ROLE_USER和ROLE_ADMIN角色的用户能够去訪问两种角色的资源。公共的资源两种角色都能够訪问。

security提供了默认的登出地址。登出后用户在spring中的缓存就清除了。




































































以上是关于spring security 3.1 实现权限控制的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security 3.1:Active Directory 身份验证和本地 DB 授权

Spring boot + Spring Security实现权限管理

Spring Security 3.1 - 发生会话超时时自动重定向到登录页面

Spring Security 3.1 + JPA - 空指针异常

Spring Security 权限管理

Spring Security 权限管理