Spring集成Apache Shiro安全框架

前段时间项目中用到Apache Shiro安全框架用于实现用户认证与授权。
参考资料:
http://www.ibm.com/developerworks/cn/web/wa-apacheshiro/
http://www.ibm.com/developerworks/cn/opensource/os-cn-shiro/
http://www.infoq.com/cn/articles/apache-shiro


配置信息

web.xml中通过spring的代理过滤器将过滤交给shiro。同时applicationContext.xml中需要一个叫shiroFilter的过滤器。
代码如下:

    
        shiroFilter
        org.springframework.web.filter.DelegatingFilterProxy
        
            targetFilterLifecycle
            true
        
    
    
        shiroFilter
        /*
    

applicationContext-shiro.xml用于shiro安全框架的配置。
代码如下:




    Shiro安全配置

    
    
        
    

    
    
        
    
    
    
    
        
        sitemesh=false
        
    
    
    

     
    
    
    
         
            
                
                
            
         
        
        
        
        
        
            
                /login = UserFormAuthenticationFilter
                /logout = logout
                /static/** = anon
                /register/** = anon
                /views/**/*.jsp = user,urlFilter
                /** = user
            
        
    
    
    
    
    

代码实现部分

ShiroDbRealm继承AuthorizingRealm类实现用户认证和授权的方法。

public class ShiroDbRealm extends AuthorizingRealm
{
    private AccountService accountService;

    public ShiroDbRealm() {
        super();
        //setCredentialsMatcher(new AllowAllCredentialsMatcher());
        //设置认证token的实现类,该处使用UsernamepasswordTken,也可自定义token,如果自定义token则需继承AuthenticationToken;
            setAuthenticationTokenClass(EhrUserToken.class);       
   }
    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException
    {
        return info;
    }
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals)
    {
        
        return info;
    }
}

自定义的过滤器继承AuthenticationFilter

public class URLFilter extends AuthenticationFilter
{

    @Override
    protected boolean onAccessDenied(ServletRequest request,
            ServletResponse response) throws Exception
    {
        HttpServletResponse rsp = (HttpServletResponse)response;
        rsp.sendError(403);
        return false;
    }

    @Override
    public void doFilterInternal(ServletRequest request,
            ServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        Exception exception = null;
        try
        {
            //授权成功
            executeChain(request, response, chain);
            postHandle(request, response);
            
            //授权失败
            onAccessDenied(request,response);   
        } catch (Exception e)
        {
             exception = e;
        }
        finally {
            cleanup(request, response, exception);
        }
    }
}

你可能感兴趣的:(Spring集成Apache Shiro安全框架)