【Apache-Shiro】shiro配置详解

Apache-Shiro旨在简化身份验证和授权,为企业应用提供安全解决方案。

1.配置web.xml

<filter>
        <filter-name>shiroFilterfilter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
        param>
            <param-name>targetFilterLifecycleparam-name>
            <param-value>trueparam-value>
        param>
    filter>
    <filter-mapping>
        <filter-name>shiroFilterfilter-name>
        /*
    

2.配置shiro.xml


<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="/user/login"/>
    <property name="successUrl" value="/company/index"/>
    <property name="filters">
        <map>
            <entry key="user" value-ref="userFilter"/>
            <entry key="authc" value-ref="formAuthenticationFilter"/>
        map>
    property>
    <property name="filterChainDefinitions">
        <ref bean="shiroFilterChainDefinitions"/>
    property>
bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<bean name="shiroFilterChainDefinitions" class="java.lang.String">
        <constructor-arg>
            <value>
                /static/** = anon
                /user/login = authc
                /user/logout = logout
                /user/** = anon
                /** = user
            value>
        constructor-arg>
    bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="systemAuthorizingRealm"/>
    <property name="sessionManager" ref="sessionManager"/>
    <property name="cacheManager" ref="shiroCacheManager"/>
bean>

<bean id="sessionManager" class="com.test.common.security.shiro.session.SessionManager">
    <property name="sessionDAO" ref="sessionDAO"/>

    
    <property name="globalSessionTimeout" value="1800000"/>

    
    <property name="sessionValidationInterval" value="120000"/>
    <property name="sessionValidationSchedulerEnabled" value="true"/>

    <property name="sessionIdCookie" ref="sessionIdCookie"/>
    <property name="sessionIdCookieEnabled" value="true"/>
bean>
<bean id="sessionDAO" class="com.test.common.security.shiro.session.CacheSessionDAO">
    <property name="sessionIdGenerator" ref="idGen"/>
    <property name="activeSessionsCacheName" value="activeSessionsCache"/>
    <property name="cacheManager" ref="shiroCacheManager"/>
bean>
<bean id="shiroCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    <property name="cacheManager" ref="cacheManager"/>
bean>

和spring-security一样,DelegatingFilterProxy是一个代理过滤器,目标过滤器是shiroFilter。而shiroFilter在配置项中是一个ShiroFilterFactoryBean工厂。其实在创建实例的时候ShiroFilterFactoryBean会创建一个SpringShiroFilter类,所以最终代理的是SpringShiroFilter.如下所示:

public Object getObject() throws Exception {
    if (instance == null) {
        instance = createInstance();
    }
    return instance;
}
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);
}

系统默认的Subject其实是DelegatingSubject类,其中的login方法是委托给securityManager来执行。

public void login(AuthenticationToken token) throws AuthenticationException {
        clearRunAsIdentitiesInternal();
        Subject subject = securityManager.login(this, token);

        PrincipalCollection principals;

        String host = null;

        if (subject instanceof DelegatingSubject) {
            DelegatingSubject delegating = (DelegatingSubject) subject;
            //we have to do this in case there are assumed identities - we don't want to lose the 'real' principals:
            principals = delegating.principals;
            host = delegating.host;
        } else {
            principals = subject.getPrincipals();
        }

        if (principals == null || principals.isEmpty()) {
            String msg = "Principals returned from securityManager.login( token ) returned a null or " +
                    "empty value.  This value must be non null and populated with one or more elements.";
            throw new IllegalStateException(msg);
        }
        this.principals = principals;
        this.authenticated = true;
        if (token instanceof HostAuthenticationToken) {
            host = ((HostAuthenticationToken) token).getHost();
        }
        if (host != null) {
            this.host = host;
        }
        Session session = subject.getSession(false);
        if (session != null) {
            this.session = decorate(session);
        } else {
            this.session = null;
        }
    }

securityManager执行的时候委托给authenticator来执行authenticate,而authenticator是ModularRealmAuthenticator类。跟踪源码如下:

protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
        if (!realm.supports(token)) {
            String msg = "Realm [" + realm + "] does not support authentication token [" +
                    token + "].  Please ensure that the appropriate Realm implementation is " +
                    "configured correctly or that the realm accepts AuthenticationTokens of this type.";
            throw new UnsupportedTokenException(msg);
        }
        AuthenticationInfo info = realm.getAuthenticationInfo(token);
        if (info == null) {
            String msg = "Realm [" + realm + "] was unable to find account data for the " +
                    "submitted AuthenticationToken [" + token + "].";
            throw new UnknownAccountException(msg);
        }
        return info;
    }

而realm就是我们定义的自定义数据源systemAuthorizingRealm。上述就是shiro认证过程。而shiro拦截请求后如何执行过滤器链的。
shiro拦截到request请求后,首先会去获取FilterChain。

protected FilterChain getExecutionChain(ServletRequest request, ServletResponse response, FilterChain origChain) {
        FilterChain chain = origChain;

        FilterChainResolver resolver = getFilterChainResolver();
        if (resolver == null) {
            log.debug("No FilterChainResolver configured.  Returning original FilterChain.");
            return origChain;
        }

        FilterChain resolved = resolver.getChain(request, response, origChain);
        if (resolved != null) {
            log.trace("Resolved a configured FilterChain for the current request.");
            chain = resolved;
        } else {
            log.trace("No FilterChain configured for the current request.  Using the default.");
        }

        return chain;
    }

以上的resolver其实是PathMatchingFilterChainResolver实例,

public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
        FilterChainManager filterChainManager = getFilterChainManager();
        if (!filterChainManager.hasChains()) {
            return null;
        }

        String requestURI = getPathWithinApplication(request);

        //the 'chain names' in this implementation are actually path patterns defined by the user.  We just use them
        //as the chain name for the FilterChainManager's requirements
        for (String pathPattern : filterChainManager.getChainNames()) {

            // If the path does match, then pass on to the subclass implementation for specific checks:
            if (pathMatches(pathPattern, requestURI)) {
                if (log.isTraceEnabled()) {
                    log.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI + "].  " +
                            "Utilizing corresponding filter chain...");
                }
                return filterChainManager.proxy(originalChain, pathPattern);
            }
        }

        return null;
    }

上面代码就是将request请求路径和filterChainDefinitions做比较。匹配上了之后会返回过滤器,然后执行该过滤器。

你可能感兴趣的:(web架构)