Spring security权限配置与使用大全

简介

Spring Security 是为了基于Spring的应用程序提供的声明式安全保护的安全性框架。Spring Security 提供了完整的安全性解决方案,它能够在Web请求级别和方法调用级别处理身份认证和授权。因为基于Spring框架,所以SPring Security充分使用了一览注入和面向切面技术。
Spring Security 本质上是借助一系列的 Servlet Filter来提供各种安全性功能,但这并不需要我们手动去添加或者创建多个Filter。实际上,我们仅需要配置一个Filter即可。
DelegatingFilterProxy 是一个特殊的Filter,他本身并没有做太多工作,而是将工作委托给了一个注入到Spring应用上下文的Filter实现类。

Spring security权限配置与使用大全_第1张图片

在本例中,主要讲解spring-security的配置与使用,实现方式为:

    1.将用户、权限、资源(url)采用数据库存储

    2.自定义过滤器,代替原有的 FilterSecurityInterceptor

    3.自定义实现 UserDetailsService、Filter、AccessDecisionManager和FilterInvocationSecurityMetadataSource并在配置文件进行相应的配置

    4.Spring-seculity在自定义用户验证的类加载必须早于Controller层创建

1.配置Spring-seculity.xml




    
    
    
    
    
    
    
    
        
        
        
    

        
        
        
        
        

        
        

    

    
    

    
    
        
            




        
    

2.配置Web.xml



    ssm-web
    
        all-admin-login.jsp
        index.htm
        index.jsp
        default.html
        default.htm
        default.jsp
    
    
    
        contextConfigLocation
        classpath:ApplicantContext.xml,classpath:spring-security.xml
    
    
    
            org.springframework.web.context.ContextLoaderListener
    
    
    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
    
    
        springSecurityFilterChain
        /*
    
    
    
        DispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:spring-mvc.xml
        
        1
    
    
        DispatcherServlet
        /
    

    
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        CharacterEncodingFilter
        /*
    

3.自定义用户角色验证

package ssm.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 ssm.bean.Role;
import ssm.bean.UserInfo;
import ssm.dao.LoginDao;

import java.util.ArrayList;
import java.util.List;

@Service("userinfo")
public class UserinfoService implements IUserInfoService{

    @Autowired
    LoginDao loginDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {    //将s传参从数据库查询是否用这个用户
        UserInfo info=loginDao.findByList(s);
        List list=info.getRoles();
         List role= new ArrayList();
        for(Role i:list){
            role.add(new SimpleGrantedAuthority("ROLE_"+i.getRolename()));
        }

        System.out.println(s);
        return new User(info.getUsername(), "{noop}"+info.getPassword(),info.getStatus()!=0?true:false,true,true,true, role);


    }

}

4.seculity自定义过滤器

package filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
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;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import java.io.IOException;



@Service("myFilter")
public class MyFilter extends AbstractSecurityInterceptor implements Filter {

    @Autowired
    private FilterInvocationSecurityMetadataSource securityMetadataSource;

    @Override
    public Class getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return securityMetadataSource;
    }

    @Autowired
    public void setMyAccessDecisionManager(MyAccessDescisionManager myAccessDescisionManager) {
        super.setAccessDecisionManager(myAccessDescisionManager);
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("------------MyFilterSecurityInterceptor.doFilter()-----------开始拦截器了....");
        FilterInvocation fi = new FilterInvocation(request, response, chain);

        InterceptorStatusToken token = super.beforeInvocation(fi);

        try {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            super.afterInvocation(token, null);
        }

        System.out.println("------------MyFilterSecurityInterceptor.doFilter()-----------拦截器该方法结束了....");
    }

    @Override
    public void destroy() {

    }
}

5.自定义用户权限验证

package filter;

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.Component;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

@Service
public class MyAccessDescisionManager implements AccessDecisionManager {
 
    @Override
    public void decide(Authentication authentication, Object object, Collection configAttributes)throws AccessDeniedException, InsufficientAuthenticationException {
        // TODO Auto-generated method stub
         System.out.println("MyAccessDescisionManager.decide()------------------验证用户是否具有一定的权限--------");  
            if(configAttributes==null) return;  
            Iterator it = configAttributes.iterator();
            while(it.hasNext()){  
                String needResource = it.next().getAttribute();  
                //authentication.getAuthorities()  用户所有的权限  
                for(GrantedAuthority ga:authentication.getAuthorities()){
                    System.out.println("ROLE_"+needResource);
                    System.out.println(ga.getAuthority());
                    if(("ROLE_"+needResource).equals(ga.getAuthority())){  
                        return;  
                    }  
                }  
            }  
            throw new AccessDeniedException("--------MyAccessDescisionManager:decide-------权限认证失败!");  
        
    }
 
    @Override
    public boolean supports(ConfigAttribute attribute) {
        // TODO Auto-generated method stub
        return true;
    }
 
    @Override
    public boolean supports(Class clazz) {
        // TODO Auto-generated method stub
        return true;
    }
 
}

6.自定义初始化用户角色和权限属性

package filter;

import org.springframework.beans.factory.annotation.Autowired;
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.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import ssm.bean.Premission;
import ssm.bean.Role;
import ssm.dao.LoginDao;
import ssm.dao.MapperRoleDao;
import ssm.dao.MapperUserDao;

import java.util.*;

@Service
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
 
    /*@Autowired
    private IUserDao userDao; */
    
    @Autowired
    private LoginDao loginDao;
  

    /* 保存资源和权限的对应关系  key-资源url  value-权限 */  
    private static Map> resourceMap = null;
    private AntPathMatcher urlMatcher = new AntPathMatcher();
      
    public MySecurityMetadataSource() {    
        //loadResourcesDefine();
    }  
      
    @Override  
    public Collection getAllConfigAttributes() {  
        return null;  
    }  
  

    private void loadResourcesDefine(){  
        resourceMap = new HashMap>();
          
        System.out.println("MySecurityMetadataSource.loadResourcesDefine()--------------开始加载资源列表数据--------");  
        List roles;
        try {
            roles = loginDao.findByROleList();
             for(Role role : roles){
                    List permissions = role.getPremission();
                    for(Premission permission : permissions){
                        Collection configAttributes = null;
                        ConfigAttribute configAttribute = new SecurityConfig(role.getRolename());
                        if(resourceMap.containsKey(permission.getUrl())){
                            configAttributes = resourceMap.get(permission.getUrl());
                            configAttributes.add(configAttribute);
                        }else{
                            configAttributes = new ArrayList() ;
                            configAttributes.add(configAttribute);
                            resourceMap.put(permission.getUrl(), configAttributes);
                        }
                    }
                }
                System.out.println("11");
                Set set = resourceMap.keySet();
                Iterator it = set.iterator();
                int  i=0;
                while(it.hasNext()){
                    String s = it.next();
                    System.out.println(++i+"key:"+s+"|value:"+resourceMap.get(s));
                }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

       
    }  
    /*  
     * 根据请求的资源地址,获取它所拥有的权限 
     */  
    @Override  
    public Collection getAttributes(Object obj)  
            throws IllegalArgumentException {  
        if(null==resourceMap||resourceMap.size() == 0) {
            loadResourcesDefine();
        }
        //获取请求的url地址  
        String url = ((FilterInvocation)obj).getRequestUrl();
        System.out.println("MySecurityMetadataSource:getAttributes()---------------请求地址为:"+url);  
        Iterator it = resourceMap.keySet().iterator();
        while(it.hasNext()){  
            String _url = it.next();  
            if(url.indexOf("?")!=-1){
                url = url.substring(0, url.indexOf("?"));
            }
            if(urlMatcher.match(_url,url)){
                System.out.println("MySecurityMetadataSource:getAttributes()---------------需要的权限是:"+resourceMap.get(_url));  
                return resourceMap.get(_url);
            }
                
        }
        Collection nouse = new ArrayList();
        nouse.add(new SecurityConfig("无相应权限"));
        return nouse;
    }  
  
    @Override  
    public boolean supports(Class arg0) {  
        System.out.println("MySecurityMetadataSource.supports()---------------------");  
        return true;  
    }  
      
}

到此这篇关于Spring-seculity权限使用的文章就介绍到这了,更多相关Spring-seculity权限使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的