參考文檔: http://wenku.baidu.com/view/4ec7e324ccbff121dd368364.html
在spring security3中使用自己定義的數據結構來實現權限設置。
- 數據庫
- 用戶表
- 角色表
- action表,即資源表
- 角色-用戶關聯表
- actiion-角色關聯表
- 配置過程
- web.xml中加入過濾器
- <!-- 配置spiring security -->
- <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>
- <!-- 配置spiring security結束 -->
- 在applicationContext.xml中import spring security部分的配置
- <import resource="security3.0_JPA.xml"/>
- 配置import resource="security3.0_JPA.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.0.xsd">
- <http auto-config="true" access-denied-page="/jsp/accessDenied.jsp">
- <intercept-url pattern="/css/**" filters="none" />
- <intercept-url pattern="/images/**" filters="none" />
- <intercept-url pattern="/js/**" filters="none" />
- <!-- 增加一個filter,這點與Acegi是不一樣的,不能修改默認的filter了,
- 這個filter位於FILTER_SECURITY_INTERCEPTOR之前 -->
- <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR" />
- </http>
- <!-- 一個自定義的filter,必須包含authenticationManager,accessDecisionManager,securityMetadataSource三個屬性,
- 我們的所有控制將在這三個類中實現,解釋詳見具體配置 -->
- <beans:bean id="myFilter" class="com.softvan.spring.security.FilterSecurityInterceptor">
- <beans:property name="authenticationManager" ref="MyAuthenticationManager" />
- <!-- 訪問決策器,決定某個用戶具有的角色,是否有足夠的權限去訪問某個資源 -->
- <beans:property name="accessDecisionManager" ref="AccessDecisionManager" />
- <beans:property name="securityMetadataSource" ref="MySecurityMetadataSource" />
- </beans:bean>
- <!-- 資源源數據定義,將所有的資源和權限對應關係建立起來,即定義某一資源可以被哪些角色訪問 -->
- <beans:bean id="MySecurityMetadataSource" init-method="loadResourceDefine" class="com.softvan.spring.security.InvocationSecurityMetadataSourceService">
- <beans:property name="roleService" ref="RoleService" />
- <beans:property name="actionService" ref="ActionService" />
- </beans:bean>
- <!-- 驗證配置 , 認證管理器,實現用戶認證的入口,主要實現UserDetailsService接口即可 -->
- <authentication-manager alias="MyAuthenticationManager">
- <authentication-provider user-service-ref="UserDetailService">
- <!--
- <s:password-encoder hash="sha" />
- -->
- </authentication-provider>
- </authentication-manager>
- </beans:beans>
- web.xml中加入過濾器
- 相關java代碼
- AccessDecisionManager.java
- /**
- *
- */
- package com.softvan.spring.security;
- import org.apache.log4j.Logger;
- /**
- * @author 徐澤宇(roamer)
- *
- * 2010-7-4
- */
- import java.util.Collection;
- import java.util.Iterator;
- 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;
- import org.springframework.stereotype.Service;
- @Service("AccessDecisionManager")
- public class AccessDecisionManager implements org.springframework.security.access.AccessDecisionManager {
- /**
- * Logger for this class
- */
- private static final Logger logger = Logger.getLogger(AccessDecisionManager.class);
- // In this method, need to compare authentication with configAttributes.
- // 1, A object is a URL, a filter was find permission configuration by this
- // URL, and pass to here.
- // 2, Check authentication has attribute in permission configuration
- // (configAttributes)
- // 3, If not match corresponding authentication, throw a
- // AccessDeniedException.
- public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
- if (logger.isDebugEnabled()) {
- logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - start"); //$NON-NLS-1$
- }
- if (configAttributes == null) {
- if (logger.isDebugEnabled()) {
- logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - end"); //$NON-NLS-1$
- }
- return;
- }
- if (logger.isDebugEnabled()){
- logger.debug("正在訪問的url是:"+object.toString());
- }
- Iterator<ConfigAttribute> ite = configAttributes.iterator();
- while (ite.hasNext()) {
- ConfigAttribute ca = ite.next();
- logger.debug("needRole is:"+ca.getAttribute());
- String needRole = ((SecurityConfig) ca).getAttribute();
- for (GrantedAuthority ga : authentication.getAuthorities()) {
- logger.debug("/t授權信息是:"+ga.getAuthority());
- if (needRole.equals(ga.getAuthority())) { // ga is user's role.
- if (logger.isDebugEnabled()) {
- logger.debug("判斷到,needRole 是"+needRole+",用戶的角色是:"+ga.getAuthority()+",授權數據相匹配");
- logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - end"); //$NON-NLS-1$
- }
- return;
- }
- }
- }
- throw new AccessDeniedException("沒有權限");
- }
- public boolean supports(ConfigAttribute attribute) {
- // TODO Auto-generated method stub
- return true;
- }
- public boolean supports(Class<?> clazz) {
- return true;
- }
- }
- FilterSecurityInterceptor.java
- /**
- *
- */
- package com.softvan.spring.security;
- import org.apache.log4j.Logger;
- /**
- * @author 徐澤宇(roamer)
- *
- * 2010-7-4
- */
- 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;
- public class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
- /**
- * Logger for this class
- */
- private static final Logger logger = Logger.getLogger(FilterSecurityInterceptor.class);
- private FilterInvocationSecurityMetadataSource securityMetadataSource;
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- if (logger.isDebugEnabled()) {
- logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - start"); //$NON-NLS-1$
- }
- FilterInvocation fi = new FilterInvocation(request, response, chain);
- invoke(fi);
- if (logger.isDebugEnabled()) {
- logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - end"); //$NON-NLS-1$
- }
- }
- 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);
- }
- }
- @Override
- public SecurityMetadataSource obtainSecurityMetadataSource() {
- return this.securityMetadataSource;
- }
- public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {
- this.securityMetadataSource = securityMetadataSource;
- }
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void init(FilterConfig filterconfig) throws ServletException {
- // TODO Auto-generated method stub
- }
- }
- InvocationSecurityMetadataSourceService.java
- /**
- *
- */
- package com.softvan.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.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.security.web.util.AntUrlPathMatcher;
- import org.springframework.security.web.util.UrlMatcher;
- import org.springframework.stereotype.Service;
- import com.alcor.acl.domain.TAction;
- import com.alcor.acl.domain.TRole;
- import com.alcor.acl.service.ActionService;
- import com.alcor.acl.service.RoleService;
- /*
- *
- * 最核心的地方,就是提供某個資源對應的權限定義,即getAttributes方法返回的結果。
- * 注意,我例子中使用的是AntUrlPathMatcher這個path matcher來檢查URL是否與資源定義匹配,
- * 事實上你還要用正則的方式來匹配,或者自己實現一個matcher。
- *
- * 此類在初始化時,應該取到所有資源及其對應角色的定義
- *
- * 說明:對於方法的spring注入,只能在方法和成員變量裏注入,
- * 如果一個類要進行實例化的時候,不能注入對象和操作對象,
- * 所以在構造函數裏不能進行操作注入的數據。
- */
- @Service("InvocationSecurityMetadataSourceService")
- public class InvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
- /**
- * Logger for this class
- */
- private static final Logger logger = Logger.getLogger(InvocationSecurityMetadataSourceService.class);
- private RoleService roleService ;
- private ActionService actionService;
- private UrlMatcher urlMatcher = new AntUrlPathMatcher();
- private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
- public void loadResourceDefine()throws Exception {
- this.resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
- //通過數據庫中的信息設置,resouce和role
- for (TRole item:this.roleService.getAllRoles()){
- Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
- ConfigAttribute ca = new SecurityConfig(item.getRoleName());
- atts.add(ca);
- List<TAction> tActionList = actionService.findByRoleID(item.getRoleId());
- //把資源放入到spring security的resouceMap中
- for(TAction tAction:tActionList){
- logger.debug("獲得角色:["+item.getRoleName()+"]擁有的acton有:"+tAction.getActionUrl());
- this.resourceMap.put(tAction.getActionUrl(), atts);
- }
- }
- /*//通過硬編碼設置,resouce和role
- resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
- Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
- ConfigAttribute ca = new SecurityConfig("admin");
- atts.add(ca);
- resourceMap.put("/jsp/admin.jsp", atts);
- resourceMap.put("/swf/zara.html", atts);*/
- }
- // According to a URL, Find out permission configuration of this URL.
- public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
- if (logger.isDebugEnabled()) {
- logger.debug("getAttributes(Object) - start"); //$NON-NLS-1$
- }
- // guess object is a URL.
- String url = ((FilterInvocation) object).getRequestUrl();
- Iterator<String> ite = resourceMap.keySet().iterator();
- while (ite.hasNext()) {
- String resURL = ite.next();
- if (urlMatcher.pathMatchesUrl(url, resURL)) {
- Collection<ConfigAttribute> returnCollection = resourceMap.get(resURL);
- if (logger.isDebugEnabled()) {
- logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$
- }
- return returnCollection;
- }
- }
- if (logger.isDebugEnabled()) {
- logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$
- }
- return null;
- }
- public boolean supports(Class<?> clazz) {
- return true;
- }
- public Collection<ConfigAttribute> getAllConfigAttributes() {
- return null;
- }
- public RoleService getRoleService() {
- return roleService;
- }
- public void setRoleService(RoleService roleService) {
- this.roleService = roleService;
- }
- public ActionService getActionService() {
- return actionService;
- }
- public void setActionService(ActionService actionService) {
- this.actionService = actionService;
- }
- }
- UserDetailService.java
- /**
- *
- */
- package com.softvan.spring.security;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Set;
- import javax.inject.Inject;
- import org.apache.log4j.Logger;
- import org.springframework.dao.DataAccessException;
- 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.alcor.acl.domain.TRole;
- import com.alcor.acl.domain.TUser;
- @Service("UserDetailService")
- public class UserDetailService implements UserDetailsService {
- /**
- * Logger for this class
- */
- private static final Logger logger = Logger.getLogger(UserDetailService.class);
- @Inject
- com.alcor.acl.component.User user ;
- public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException {
- if (logger.isDebugEnabled()) {
- logger.debug("loadUserByUsername(String) - start"); //$NON-NLS-1$
- }
- Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();
- String password=null;
- //取得用戶的密碼
- TUser tUser = user.getUserByName(username);
- if (tUser ==null){
- String message = "用戶"+username+"不存在";
- logger.error(message);
- throw new UsernameNotFoundException(message);
- }
- password=user.getUserByName(username).getPassword();
- //獲得用戶的角色
- Set<TRole> tRoles =tUser.getTRoles();
- for(TRole item : tRoles){
- GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl(item.getRoleName());
- if (logger.isDebugEnabled()){
- logger.debug("用戶:["+tUser.getName()+"]擁有角色:["+item.getRoleName()+"],即spring security中的access");
- }
- auths.add(grantedAuthorityImpl);
- }
- User user = new User(username,password, true, true, true, true, auths);
- if (logger.isDebugEnabled()) {
- logger.debug("loadUserByUsername(String) - end"); //$NON-NLS-1$
- }
- return user;
- }
- }
- AccessDecisionManager.java