1. 程式人生 > >spring security 3.1 實現權限控制

spring security 3.1 實現權限控制

ref bmi sage pan 管理系統 dao 數據庫 ng- nds

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();
	[email protected]("ROLE_ADMIN")//擁有ROLE_ADMIN權限的用戶才可進入此方法
	boolean addreport_admin();
	[email protected]("ROLE_ADMIN")
	boolean deletereport_admin();
	
	Users findbyUsername(String name);
	[email protected]("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 實現權限控制