文档章节

Shiro源码分析之ShiroFilterFactoryBean

Lucare
 Lucare
发布于 2018/07/22 00:19
字数 859
阅读 13
收藏 0

创建核心Filter

同其他框架一样,都有个切入点,这个核心Filter就是拦截所有请求的。

通过web.xml中配置的Filer进入,执行init方法获取这个instance,调用下面的createInstance方法创建核心Filter:

protected AbstractShiroFilter createInstance() throws Exception {

    log.debug("Creating Shiro Filter instance.");

    SecurityManager securityManager = getSecurityManager();
    if (securityManager == null) {
        String msg = "SecurityManager property must be set.";
        throw new BeanInitializationException(msg);
    }

    if (!(securityManager instanceof WebSecurityManager)) {
        String msg = "The security manager does not implement the WebSecurityManager interface.";
        throw new BeanInitializationException(msg);
    }

    FilterChainManager manager = createFilterChainManager();

    //Expose the constructed FilterChainManager by first wrapping it in a
    // FilterChainResolver implementation. The AbstractShiroFilter implementations
    // do not know about FilterChainManagers - only resolvers:
    PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
    chainResolver.setFilterChainManager(manager);

    //Now create a concrete ShiroFilter instance and apply the acquired SecurityManager and built
    //FilterChainResolver.  It doesn't matter that the instance is an anonymous inner class
    //here - we're just using it because it is a concrete AbstractShiroFilter instance that accepts
    //injection of the SecurityManager and FilterChainResolver:
    return new SpringShiroFilter((WebSecurityManager) securityManager, chainResolver);
}

createFilterChainManager方法比较重要,包含以下必要操作:

  1. DefaultFilterChainManager对象的创建

  2. defaultFilters的获取和相关url的填充

  3. 自定义filters的获取和相关url的填充

  4. 获取FilterChainDefinitionMap (这个就是配置文件中的filterChainDefinitions的映射关系)

  5. 对url和权限的映射关系作处理

默认的DefaultFilter枚举中包含以下filter类:

anon(AnonymousFilter.class),
authc(FormAuthenticationFilter.class),
authcBasic(BasicHttpAuthenticationFilter.class),
logout(LogoutFilter.class),
noSessionCreation(NoSessionCreationFilter.class),
perms(PermissionsAuthorizationFilter.class),
port(PortFilter.class),
rest(HttpMethodPermissionFilter.class),
roles(RolesAuthorizationFilter.class),
ssl(SslFilter.class),
user(UserFilter.class);

执行doFilter方法

看下内部类 SpringShiroFilter:

private static final class SpringShiroFilter extends AbstractShiroFilter {

    protected SpringShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
        super();
        if (webSecurityManager == null) {
            throw new IllegalArgumentException("WebSecurityManager property cannot be null.");
        }
        setSecurityManager(webSecurityManager);
        if (resolver != null) {
            setFilterChainResolver(resolver);
        }
    }
}

这里写图片描述

在org.apache.shiro.web.servlet.OncePerRequestFilter中实现了doFilter方法:

public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName();
    if ( request.getAttribute(alreadyFilteredAttributeName) != null ) {
        log.trace("Filter '{}' already executed.  Proceeding without invoking this filter.", getName());
        filterChain.doFilter(request, response);
    } else //noinspection deprecation
        if (/* added in 1.2: */ !isEnabled(request, response) ||
            /* retain backwards compatibility: */ shouldNotFilter(request) ) {
        log.debug("Filter '{}' is not enabled for the current request.  Proceeding without invoking this filter.",
                getName());
        filterChain.doFilter(request, response);
    } else {
        // Do invoke this filter...
        log.trace("Filter '{}' not yet executed.  Executing now.", getName());
        request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);

        try {
            doFilterInternal(request, response, filterChain);
        } finally {
            // Once the request has finished, we're done and we don't
            // need to mark as 'already filtered' any more.
            request.removeAttribute(alreadyFilteredAttributeName);
        }
    }
}

三种情况,分为两条路线:

  1. filterChain.doFilter(request, response); 直接放行
  2. doFilterInternal(request, response, filterChain); 走子类实现

在org.apache.shiro.web.servlet.AbstractShiroFilter实现doFilterInternal:

protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse, final FilterChain chain)
        throws ServletException, IOException {

    Throwable t = null;

    try {
        final ServletRequest request = prepareServletRequest(servletRequest, servletResponse, chain);
        final ServletResponse response = prepareServletResponse(request, servletResponse, chain);

        final Subject subject = createSubject(request, response);

        //noinspection unchecked
        subject.execute(new Callable() {
            public Object call() throws Exception {
                updateSessionLastAccessTime(request, response);
                executeChain(request, response, chain);
                return null;
            }
        });
    } catch (ExecutionException ex) {
        t = ex.getCause();
    } catch (Throwable throwable) {
        t = throwable;
    }

    if (t != null) {
        if (t instanceof ServletException) {
            throw (ServletException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        //otherwise it's not one of the two exceptions expected by the filter method signature - wrap it in one:
        String msg = "Filtered request failed.";
        throw new ServletException(msg, t);
    }
}

将HttpServletRequest和HttpServletResponse包装成shiro自己的ShiroHttpServletRequest和ShiroHttpServletResponse。

利用包装后的对象创建Subject。

然后是执行subject的execute的方法。

protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain)
        throws IOException, ServletException {
    FilterChain chain = getExecutionChain(request, response, origChain);
    chain.doFilter(request, response);
}

获取的FilterChain是一个代理的ProxiedFilterChain,持有自己的Filter集合,重写doFilter方法:取自己持有的Filter集合,一个个执行其doFilter方法,当所有的Filter都执行完后,再执行servlet的FilterChain。

后面的过程就是一个原始的FilterChain的执行过程。

可以想象,原生的Filter链似乎也是这样一个执行过程,遍历web.xml中配置的所有Filter。

整个过程就是代理模式的运用。

这里写图片描述

© 著作权归作者所有

Lucare

Lucare

粉丝 6
博文 11
码字总数 11404
作品 0
深圳
程序员
私信 提问
Shiro源码分析之ShiroFilterFactoryBean

一、Spring 的DelegatingFilterProxy如何发现 Shiro 的ShiroFilterFactoryBean 简单的回顾一下,web.xml配置中的Spring DelegatingFilterProxy 的这个Filter是如何找到WebApplicationcontext......

0909
2016/08/12
296
0
shiro登录流程

ShiroFilter Shiro提供了与Web集成的支持,其通过一个ShiroFilter入口来拦截需要安全控制的URL,然后进行相应的控制,ShiroFilter类似于如Strut2/SpringMVC这种web框架的前端 其是安全控制的...

嘿嘿!!
2016/10/20
0
0
Spring与Shiro整合源码分析

Spring与Shiro整合是通过在web.xml里面配置过滤器: 然后我们在apllicationContext.xml里面配置如下的ShiroFilterFactoryBean就可以了 为什么这样配置就可以了?我们并没有在web.xml配置shi...

zpassion
2016/09/14
228
0
一步一步教你用shiro——1引入shiro框架

一步一步教你用shiro——1引入shiro框架 一步一步教你用shiro——2配置并自定义realm 一步一步教你用shiro——3配置并自定义sessionManager 一步一步教你用shiro——4配置并自定义sessionDa...

肥肥小浣熊
2018/04/30
0
0
Java权限框架Shiro过滤连源码解读

由于公司要求我对我司的框架的权限模块进行整理,所以最近看了Shiro这个框架的源码,里面有一些思想还是非常值得学习的,记录一下 入口 官网提供了很多种权限的demo,提供web、spring支持、A...

小彬彬_
2016/08/22
179
1

没有更多内容

加载失败,请刷新页面

加载更多

家庭作业——苗钰婷

2 编写一个程序,发出一声警报,然后打印下面的文本: Startled by the sudden sound, Sally shouted, "By the Great Pumpkin, what was that! #include<stdio.h>int main(){......

OSC_Okruuv
9分钟前
1
0
经典系统设计面试题解析:如何设计TinyURL(一)

原文链接: https://www.educative.io/courses/grokking-the-system-design-interview/m2ygV4E81AR 编者注:本文以一道经典的系统设计面试题:《如何设计TinyURL》的参考答案和解析为例,帮助...

APEMESH
10分钟前
1
0
2.面向对象设计原则(7条)

开闭原则 开闭原则的含义是:当应用的需求改变时,在不修改软件实体的源代码或者二进制代码的前提下,可以扩展模块的功能,使其满足新的需求。 实现方法 可以通过“抽象约束、封装变化”来实...

Eappo_Geng
12分钟前
1
0
8086汇编基础 debug P命令 一步完成loop循环

    IDE : Masm for Windows 集成实验环境 2015     OS : Windows 10 x64 typesetting : Markdown    blog : my.oschina.net/zhichengjiu    gitee : gitee.com/zhichengjiu   ......

志成就
16分钟前
1
0
使用nodeJS实现前端项目自动化之项目构建和文件合并

本文转载于:专业的前端网站➜使用nodeJS实现前端项目自动化之项目构建和文件合并 前面的话   一般地,我们使用构建工具来完成项目的自动化操作。本文主要介绍如何使用nodeJS来实现简单的项...

前端老手
30分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部